列表、集合、字典推导式快速生成列表

由输出项,列表项,过滤项组成,过滤项为bool值可省略
[expr for itm in collection if condition] 列表常规推导
(expr for itm in collection if condition) 列表迭代推导
{expr for itm in collection if condition} 字典/集合推导

列表推导

num = [1, 4, -5, 10, -7, 2, 3, -1]
filtered_and_squared = [ x**2 for x in num if x > 0]
print filtered_and_squared

# [1, 16, 100, 4, 9]

由于列表推导时会将整个列表加载到内存,对于比较大的对象请使用生成器,一次只加载一个列表元素到内存。用法同上,只需要把方括号改成圆括号。使用for in来依次取出各元素

num = [1, 4, -5, 10, -7, 2, 3, -1]
new = ( x**2 for x in num if x > 0)
for i in new:
    print i
# 1, 16, 100, 4, 9

集合推导

li = [1,2,3,4,5,6,4,3,5,12]
tmp = {i * i for i in li}
# set([1, 36, 9, 144, 16, 25, 4])

字典推导

li = [1,2,3,4,5,6,4,3,5,12]
tmp = {i: i * i for i in li}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 12: 144}

字典推导只是比集合推导多一个键处理

你可能感兴趣的:(列表、集合、字典推导式快速生成列表)