列表推导式和生成器表达式
列表推导式
固定语法 [i for i in a if ***]
示例:获取偶数
a = [1,2,3,4] x = [] for i in a: if i%2 == 0: x.append(i) a = x print(a) #[2,4]
使用列表推导式:
a = [1,2,3,4] a = [i for i in a if i%2 == 0] print(a) #[2,4]
列表推导式可以调用函数:
a = [1,2,3,4] b = [i*i for i in a] print(b) # [1, 4, 9, 16] 如果调用函数: a = [1,2,3,4] def pingfang(x): return x*x b = [pingfang(i) for i in a] print(b) # [1, 4, 9, 16]
生成器表达式
语法:把列表推导式的[]换成()
a = [1,2,3,4] a = ['%s个鸡蛋'%i for i in a] #列表推导式 print(a) # ['1个鸡蛋', '2个鸡蛋', '3个鸡蛋', '4个鸡蛋']
转换如下:
a = [1,2,3,4] a = ('老母鸡下%s个蛋'%i for i in a) #生成器表达式 a是一个生成器 g = a print(next(g)) print(next(g)) print(next(g)) print(next(g)) #老母鸡下1个蛋 # 老母鸡下2个蛋 # 老母鸡下3个蛋 # 老母鸡下4个蛋
字典推导式
和列表推导式类似
示例:把字典的key与value对换
dic = {'a':1,'b':2} dic = {dic[k]:k for k in dic} print(dic) # {1: 'a', 2: 'b'}