欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python技巧 列表推导

程序员文章站 2022-06-03 08:16:47
val = [expression for value in collection if condition]等价于val = []for value in collection: if condition: val.append(expression)列表推导在python2中存在变量泄漏的问题: ......

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