我从未见过的“i for j in”的列表迭代
我正在尝试理解下面这段Python代码的作用
plain_list = [ j for i in arguments for j in i ]
我从来没见过这样的语法,有人能帮我解释一下吗?
1 个回答
13
这叫做列表推导式。
如果用普通的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]
>>>