六. python推导式
一 .推导式 表达式
1.列表推导式
# 列表推到式 egg=['鸡蛋%s'%i for i in range(10)] # 列表推导式 print(egg) aa=[i for i in range(10)] print(aa) bb=[i*2 for i in range(10)] print(bb) eggl=[] for i in range(10): eggl.append("鸡蛋%s"%i) print(eggl)
2.生成器表达式
# 生成器表达式 g=(i for i in range(10)) print(g) # 打印结果是一个生成器 generator # 生成器表达式和列表推导式 # 不同点:括号不一样 返回值不一样 几乎不占内存
f=("鸡蛋%s"%i for i in range(10)) print(f) for i in f: print(i)
3. 三元运算符
# 三元运算符
cc=22 if 22>21 else 21
print(cc)
4.字典推导式
# 字典推导式 aa={'a':1,'b':2} dic = {v: k for k, v in aa.items()} print(dic)
5.set集合推导式 集合要去重
# set集合推导式 集合要去重 j = {x*2 for x in [1, 1, 2,2]} print(j)
6.各种推导式
# 各种推导式 aa=[i for i in range(30) if i%3==0] print(aa) aa=[i*i for i in range(30) if i%3==0] # 完整的列表推导式 print(aa) name=[["aa","bb","cc"],["1","2","3"]] for i in name: for a in i: print(a)
推导式案例
""" # 过滤掉长度小于3的字符串 并将剩下转换成大写字母 ll=["name BB","lover_ll","nice_DDD","bbb","aa"] aa=[ name.upper() for name in ll if len(name)>3] print(aa) """ # 求(x,y)其中x是0-5之间的偶数 y是0-5之间奇数组成元祖列表 lst=[(i,n) for i in range(5) for n in range(5) if i%2==0 and n%2==1] print(lst) # [(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)] # 从 m=[[1,2,3],[4,5,6],[7,8,9]] 提取 3 6 9 m=[[1,2,3],[4,5,6],[7,8,9]] for i in m: print(i[2]) aa =[ i[2] for i in m] print(aa) print([[i-0,i-1,i-2]for i in [3,6,9]]) # [[3, 2, 1], [6, 5, 4], [9, 8, 7]] # 找出求50 以内能被三整除的数求平方 bb=[ i**2 for i in range(10) if i%3==0] print(bb) # [0, 9, 36, 81] # 构造成[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] cc= [(i,i+1) for i in range(5)] print(cc) [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)] dd=[ i for i in range(20) if i%2==0] print(dd) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] li=["张三","李四","王五"] print( [el+str(index) for index ,el in enumerate(li)]) # '张三0', '李四1', '王五2'] print([ li[i]+str(i) for i in range(len(li))]) # ['张三0', '李四1', '王五2']