繁体   English   中英

Python中的嵌套列表理解

[英]Nested List comprehension in Python

我在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
>>>

我究竟做错了什么?

*我的问题的答案不是如上所述的副本,它低于这个问题。

你的列表理解中的for循环顺序相反 -

bb = [num for numbers in aa for num in numbers]

演示 -

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM