在阅读official tutorial时,我遇到了以下示例:
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
我不明白,所以我做了一些实验:
^{pr2}$我现在更糊涂了!在
所以,我的问题是:我应该按照什么顺序阅读列表理解?在
编辑:我确定我没有在任何地方定义值为9的num
变量。在
sunqingyaos-MacBook-Air:Documents sunqingyao$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> num
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num' is not defined
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [num for elem in vec]
[9, 9, 9]
>>> [num for elem in (vec for num in elem)]
[9, 9, 9]
>>>
列表理解中的循环是从左到右读取的。如果你的列表理解被写为普通循环,它看起来像这样:
在Python 2中,list comprehension中的变量共享外部作用域,因此
^{pr2}$num
可供以后使用:请注意,在Python 3上的行为是不同的:
不用担心:)。在
当您执行list comprehension时,}。您将得到一个
num
的值是9
,所以下次您迭代{9
的列表。在看这个。在
相关问题 更多 >
编程相关推荐