了解Python中的列表推导 [英] Understanding List Comprehensions in Python
问题描述
在阅读官方教程时,我遇到了这个示例:
When reading the official tutorial, I encountered this example:
>>> 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]
我听不懂,所以做了一些实验:
I couldn't understand this, so I did some experiments:
>>> [num for elem in vec]
[9, 9, 9]
>>> [num for elem in (vec for num in elem)]
[9, 9, 9]
我现在更加困惑!
所以,我的问题是:应该以什么顺序阅读列表理解?
So, my question is: In which order should I read a list comprehension?
我确定我没有在任何地方定义值为9的num
变量.
I'm sure I haven't defined a num
variable with the value 9 anywhere.
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]
>>>
推荐答案
列表理解中的循环是从左到右读取的.如果您的列表理解将被编写为普通循环,它将看起来像这样:
The loops in list comprehension are read from left to right. If your list comprehension would be written as ordinary loop it would look something like this:
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> l = []
>>> for elem in vec:
... for num in elem:
... l.append(num)
...
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
在Python 2中,列表推导中的变量共享外部范围,因此num
可在以后使用:
In Python 2 the variables within the list comprehension share the outer scope so num
is available to be used later:
>>> 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
9
请注意,在Python 3上,行为是不同的:
Note that on Python 3 behavior is different:
>>> 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
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'num' is not defined
这篇关于了解Python中的列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!