所以我觉得这是很容易解释,如果我告诉一个例子:如何根据列表中的索引创建两个新列表?
things = ["black", 7, "red', 10, "white", 15]
两个基于索引是否为偶数或奇数的新名单。
color = ["black", "red","white"]
size = [7,10,15]
所以我觉得这是很容易解释,如果我告诉一个例子:如何根据列表中的索引创建两个新列表?
things = ["black", 7, "red', 10, "white", 15]
两个基于索引是否为偶数或奇数的新名单。
color = ["black", "red","white"]
size = [7,10,15]
In [4]: things = ["black", 7, "red", 10, "white", 15]
In [5]: color = things[::2]
In [6]: color
Out[6]: ['black', 'red', 'white']
In [7]: size = things[1::2]
In [8]: size
Out[8]: [7, 10, 15]
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)
列表MANIP部分[(x,things[things.index(x)+1]) for x in things[::2]]
方式隔开分成3个列表对(就像它准备一本字典什么的...所以克雷Cray公司)
的zip(*
部分,圈整个阵列在它旁边
如果你只是做了[(x,things[things.index(x)+1]) for x in things[::2]]
withotu zip部分,那么你可以调用dict()
就可以了,并返回一个字典,whic h可能更有用
>>> 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',''] – slopeofhope 2014-10-02 22:26:36
颜色=颜色[:: 2]打印颜色 [u'Black,\ xa06',''] – slopeofhope 2014-10-02 22:27:47
@ slopeofhope:因为它们不在列表中交替。 – inspectorG4dget 2014-10-02 22:41:35