Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何根据列表中的索引创建两个新列表?_Python - Fatal编程技术网

Python 如何根据列表中的索引创建两个新列表?

Python 如何根据列表中的索引创建两个新列表?,python,Python,因此,如果我举一个例子,我认为解释起来要容易得多: things = ["black", 7, "red', 10, "white", 15] 基于索引是偶数还是奇数的两个新列表 color = ["black", "red","white"] size = [7,10,15] 在things[::2]]中的x的列表manip部分[(x,things[things.index(x)+1])将其分为3个列表对(几乎就像它准备好用于词典或其他东西一样…所以cray cray) zip(*部分将

因此,如果我举一个例子,我认为解释起来要容易得多:

things = ["black", 7, "red', 10, "white", 15] 
基于索引是偶数还是奇数的两个新列表

color = ["black", "red","white"]
size = [7,10,15]
在things[::2]]中的x的列表manip部分
[(x,things[things.index(x)+1])
将其分为3个列表对(几乎就像它准备好用于词典或其他东西一样…所以cray cray)

zip(*
部分将整个数组翻转过来

如果您只是对things[::2]中的x执行
[(x,things[things.index(x)+1])
而不使用zip部分,那么您可以调用
dict()
,并返回字典,这可能会更有用

>>> a = [(x,things[things.index(x)+1]) for x in things[::2]]
>>> a
[('black', 7), ('red', 10), ('white', 15)]
>>> cool_dict = dict(a)
>>> cool_dict['black']
7

为什么它在这个例子上不起作用?有什么想法吗?颜色=[u'Black,\xa06',u'Black,\xa06.5',''颜色=颜色[::2]打印颜色[u'Black,\xa06',''@slopeofhope:因为它们在列表中不交替。你是什么意思?你有解决方案吗?我明白你现在的意思了。你有解决方案吗?
things = ["black", 7, "red", 10, "white", 15]
two_lists = zip(*[(x,things[things.index(x)+1]) for x in things[::2]])

>>> two_lists[0]
('black', 'red', 'white')
>>> two_lists[1]
(7, 10, 15)
>>> a = [(x,things[things.index(x)+1]) for x in things[::2]]
>>> a
[('black', 7), ('red', 10), ('white', 15)]
>>> cool_dict = dict(a)
>>> cool_dict['black']
7