如何使用列表推导从zip()创建每个元素的列表?

时间:2014-02-28 00:30:22

标签: python list zip tuples list-comprehension

keys = zip([x for x in range(0, 10)], [x for x in range(0, 10)])
print keys

结果(带元组的列表):

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]

如何将每个元素设为列表而不是元组?以下示例不起作用:

keys = list(zip([x for x in range(0, 10)], [x for x in range(0, 10)]))

以下示例也不起作用:

keys = zip([x for x in range(0, 10)], [x for x in range(0, 10)])
for i in keys:
    i = list(i)
print keys

1 个答案:

答案 0 :(得分:4)

您可以使用此列表解析将元组zip的转换转换为列表:

>>>keys = [list(t) for t in zip(range(10), range(10))]
>>>keys
[[0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9]]

顺便说一句[x for x in range(0,10)]过度,只需执行range(10)

没有列表理解的另一种方法是:map(list, zip(range(10), range(10)))但是对于Python 3,这将不会返回列表,它将返回map对象。