如何基于列表中的索引创建两个新列表?

时间:2014-10-02 21:59:05

标签: python

所以我认为如果我展示一个例子就更容易解释:

things = ["black", 7, "red', 10, "white", 15] 

基于索引是偶数还是奇数的两个新列表。

color = ["black", "red","white"]
size = [7,10,15]

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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)

列表操作部分[(x,things[things.index(x)+1]) for x in things[::2]]将其分成3个列表对(几乎就像它准备好了字典或其他东西......所以cray cray)

zip(*部分,将整个数组放在一边

如果您刚刚使用zip部件[(x,things[things.index(x)+1]) for x in things[::2]],那么您可以在其上调用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