它们是可以轻松创建字典和列表的语法结构。
由输出项,列表项,过滤项组成,过滤项为bool值可省略
[expr for itm in collection if condition] 列表常规推导
由输出项,列表项,过滤项组成,过滤项为bool值可省略
[expr for itm in collection if condition] 列表常规推导
lst = [11,22,33,44] result = [i for i in range(10) if i%2==0] print(result) #注意是==,否则报错 lst = [11,22,33,44] result = [i for i in lst if i%2==0] print(result)
zero = [0,-1,5,3,-9,-3,6,2] zero_list = [x**2 for x in zero if x >0] print(zero_list)
(expr for itm in collection if condition) 列表迭代推导,
也可以说是生成器表达式,这个给出的结果是一个生成器
lst = [11,22,33,44] result = (i for i in lst if i%2==0) print(result)
{key: value for (key, value) in iterable}字典推导
lst=[1,2,3,4,5] res={i:'python'+str(i)+'期' for i in lst if i>3} print(res)
打印结果:{4: 'python4期', 5: 'python5期'}
{expr for itm in collection if condition} 集合推导
lst=[1,2,3,4,5,5,2,3] res={i for i in lst if i>0} print(res) # 结果直接过滤重复元素
{1, 2, 3, 4, 5}