2014-10-02 77 views

回答

8
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] 
+0

这是怎么回事,在这种情况下不起作用?任何想法?颜色= [u'Black,\ xa06',u'Black,\ xa06.5',''] – slopeofhope 2014-10-02 22:26:36

+0

颜色=颜色[:: 2]打印颜色 [u'Black,\ xa06',''] – slopeofhope 2014-10-02 22:27:47

+0

@ slopeofhope:因为它们不在列表中交替。 – inspectorG4dget 2014-10-02 22:41:35

0
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 
相关问题