python技巧 列表推导
val = [expression for value in collection if condition]
等价于
val = []
for value in collection:
if condition:
val.append(expression)
列表推导在python2中存在变量泄漏的问题:
>>> i=1
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> i
9
python 3中已经修复:
In [2]: i=1
In [3]: [i for i in range(10)]
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [4]: i
Out[4]: 1