什么是列表推导
大部分使用Python的人都用过它, 但却不知道它的名字.
列表推导, List Comprehension, 是Python的特色语法, 用于根据已有的可迭代对象生成一个新的list
.
例如, 根据a
生成b
, b
中的每一个元素是a
中对应位置元素值的平方.
用for
循环可以这么写:
a = range(10)
b = []
for i in a:
b.append(i * i)
用列表推导则是这么写:
a = range(10)
b = [i * i for i in a]
很明显, 从可读性上来讲, 列表推导的代码更容易理解.
缺点
在Python里, 变量作用域的概念很薄弱. 例如, 在上面的使用for
的示例里, 变量i
可以在for
循环之外访问. 使用列表推导时也会需要使用临时变量. Python2.x里的列表推导临时变量可以在[]
之外访问:
a = range(10)
i = 'hello'
print('before list comp', i)
b = [i * i for i in a]
print('after list comp', i)
用Python2.7执行, 输出为:
('before list comp', 'hello')
('after list comp', 9)
可以看到, 在列表推导执行前后, []
之外的i
的值发生了变化.
这种变量泄漏
可能会在不经意间造成bug. Python3里改进了这个缺点. 若使用Python3执行上面的代码, 输出为:
before list comp hello
after list comp hello