for循环中的循环的python list comprehension

时间:2015-12-04 06:12:46

标签: python list-comprehension

转换的节拍方式:

[(1, 2), (3, 4)] => [1, 2, 3, 4]

我试过

[i for i in row for row in [(1, 2), (3, 4)]]

但它不起作用。

3 个答案:

答案 0 :(得分:2)

您也可以使用来自itertools的链

来执行此操作
from itertools import chain
a = [(1, 2), (3, 4)]
print(list(chain.from_iterable(a)))

>>>>[1, 2, 3, 4]

答案 1 :(得分:1)

列表理解是执行此操作的最佳方式

>>> L = [(1, 2), (3, 4)]
>>> [j for i in L for j in i]
[1, 2, 3, 4]

请注意,“外环”变量需要先来

答案 2 :(得分:1)

>>> [i for row in [(1, 2), (3, 4)] for i in row]
[1, 2, 3, 4]
>>> 
[i for row in [(1, 2), (3, 4)] for i in row]
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^  # you need define 'row' before define 'i'