列出我从未见过的'i for j in'的迭代

时间:2014-03-04 19:26:06

标签: python

我试图了解以下python代码的作用

plain_list = [ j for i in arguments for j in i ]

我从未见过这样的语法,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:12)

它被称为list comprehension

使用普通的for循环,其等效代码为:

plain_list = []               # Make a list plain_list
for i in arguments:           # For each i in arguments (which is an iterable)
    for j in i:               # For each j in i (which is also an iterable)
        plain_list.append(j)  # Add j to the end of plain_list

以下是用于展平列表列表的演示:

>>> arguments = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
>>> plain_list = [ j for i in arguments for j in i ]
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> plain_list = []
>>> for i in arguments:
...     for j in i:
...         plain_list.append(j)
...
>>> plain_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>