[英]Nested List comprehension in Python
I have a List inside of a List in Python and i want to convert them into a single list using List comprehension: 我在Python中的List中有一个List,我想使用List comprehension将它们转换为单个列表:
>>> aa = [[1,2],[1,2]]
>>> bb = [num for num in numbers for numbers in aa]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'numbers' is not defined
>>>
What am i doing wrong? 我究竟做错了什么?
*The answer to my question isn't on the duplicate as stated above, it is below this question. *我的问题的答案不是如上所述的副本,它低于这个问题。
You have the for
loops in your list comprehension in the opposite order - 你的列表理解中的
for
循环顺序相反 -
bb = [num for numbers in aa for num in numbers]
Demo - 演示 -
>>> aa = [[1,2],[1,2]]
>>> bb = [num for numbers in aa for num in numbers]
>>> bb
[1, 2, 1, 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.