[英]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.