一.列表推导式
通过一行循环判断,遍历出一系列数据的方式就是推导式
特点:方便,简洁,可以实现一些简单的功能
推导式当中只能跟循环和判断(单项分支)
种类分为三种: 列表推导式 集合推导式 字典推导式
1.推导式内容讲解
#(1) 基本语法
#例:
#[1,2,3,4] => [2,4,6,8]
lst = [1,2,3,4]
lst2 = []
for i in lst:
res = i * 2
lst2.append(res)
print(lst2)
res = [i for i in range(1,5)]
print(res)
#[1, 2, 3, 4]
#改写
res2 = [i*2 for i in range(1,5)]
print(res2)
[2, 4, 6, 8]
#[1,2,3,4] => [2,8,24,64]
'''
解析:
1 ->2 乘以2的1次幂
2 ->8 乘以2的2次幂
3 ->24 乘以2的3次幂
4 ->64 乘以2的4次幂
'''
#把想要的值 写在for的左侧
res = [i<<i for i in range(1,5)] # 1<<1 2<<2 3<<3 4<<4
print(res)
#(2)带有条件判断的推导式
#例:
lst = [1,2,3,4,5,6,67,7,8,98,9]
lst2 = []
for i in lst:
if i % 2 == 0:
lst2.append(i)
print(lst2)
#推导式写法
res = [ i for i in lst if i % 2 == 0 ]
print(res)
#(3)多循环推导式
#例:
lst1 = ["one","two","three","four"]
lst2 = ["five","six","seven","eight"]
lst = []
for i in lst1:
for j in lst2:
res = i +"♥♥♥"+j
lst.append(res)
print(lst)
res = [ i +"♥♥♥"+j for i in lst1 for j in lst2 ]
print(res)
#效果为:
['one♥♥♥five', 'one♥♥♥six', 'one♥♥♥seven', 'one♥♥♥eight', 'two♥♥♥five', 'two♥♥♥six', 'two♥♥♥seven', 'two♥♥♥eight', 'three♥♥♥five', 'three♥♥♥six', 'three♥♥♥seven', 'three♥♥♥eight', 'four♥♥♥five', 'four♥♥♥six', 'four♥♥♥seven', 'four♥♥♥eight']
#分析,one循环4次才到下一个元素
#(4)带有判断条件的多循环推导式
#例:
lst1 = ["one","two","three","four"]
lst2 = ["five","six","seven","eight"]
lst_new = []
for i in lst1:
for j in lst2:
if lst1.index(i) == lst2.index(j) :
strvar = i + '♥♥♥' + j
lst_new.append(strvar)
print(lst_new)
#推导式方式实现:
res = [ i + '♥♥♥' + j for i in lst1 for j in lst2 if lst1.index(i) == lst2.index(j)]
print(res)
#在循环内加一个元素索引相等的判断:lst1.index(i) == lst2.index(j)
#结果为:
['one♥♥♥five', 'two♥♥♥six', 'three♥♥♥seven', 'four♥♥♥eight']
2.推导式练习题
#(1){'x': 'A', 'y': 'B', 'z': 'C' } 把字典写成x=A,y=B,z=C的列表推导式
dic = {'x': 'A', 'y': 'B', 'z': 'C' }
# for a,b in dic.items():
# print(a,b)
res = [a+"="+b for a,b in dic.items()]
print(res)
#(2)把列表中所有字符变成小写 ["ADDD","dddDD","DDaa","sss"]
lst = ["ADDD","dddDD","DDaa","sss"]
res = [i.lower() for i in lst]
print(res)
#(3)x是0-5之间的偶数,y是0-5之间的奇数,把x,y组成一起变成元祖,放到列表当中
#分析:
# (0 2 4)
# (1 3 5)
# (0 1) (0 3) (0 5)
# (2 1) (2 3) (2 5)
# (4 1) (4 3) (4 5)
lst_new = []
for i in range(0,6):
if i % 2 == 0:
for j in range(0,6):
if j %2 == 0:
lst_new.append((i,j))
print(lst_new)
#写法一:
res = [(i,j) for i in range(0,6) if i % 2 == 0 for j in range(0,6) if j % 2 == 1]
print(res)
lst_new2 = []
for i in range(0,6):
for j in range(0,6):
if i % 2 == 0 and j % 2 == 1:
lst_new2.append((i,j))
print(lst_new2)
#写法二:推导式方式表达
res = [(i,j) for i in range(0,6) for j in range(0,6) if i % 2 == 0 and j % 2 == 0]
print(res)
#(4)使用列表表达式 制作99乘法表的运算
#普通方法:
for i in range(1,10):
for j in range(1,i+1):
# print("%d*%d=%2d " % (i,j,i*j))
print("{:d}*{:d} ={:2d}".format(i,j,i*j),end="")
print()
#写法一:推导式表达
res = ["{:d}*{:d} ={:2d}".format(i,j,i*j) for i in range(1,10) for j in range(1,i+1)]
print(res)
#普通方法:
for i in range(9,0,-1):
for j in range(1,i+1):
# print("%d*%d=%2d " % (i,j,i*j))
print("{:d}*{:d} ={:2d}".format(i,j,i*j),end="")
print()
#写法二:推导式表达
res = ["{:d}*{:d} ={:2d}".format(i,j,i*j) for i in range(9,0,-1) for j in range(1,i+1)]
print(res)
(5)#求M,N中矩阵和元素的乘积
# M = [ [1,2,3],
# [4,5,6],
# [7,8,9] ]
# N = [ [2,2,2],
# [3,3,3],
# [4,4,4] ]
=>实现效果1 [2, 4, 6, 12, 15, 18, 28, 32, 36]
=>实现效果2 [[2, 4, 6], [12, 15, 18], [28, 32, 36]]
M = [[1,2,3],[4,5,6],[7,8,9]]
N = [[2,2,2],[3,3,3],[4,4,4]]
#分析:
#M[0][0]*N[0][0] = 2
#M[0][1]*N[0][1] = 4
#M[0][2]*N[0][2] = 6
#
#M[1][0]*N[1][0] = 12
#M[1][1]*N[1][1] = 15
#M[1][2]*N[1][2] = 18
#M[2][0]*N[2][0] = 28
#M[2][1]*N[2][1] = 32
#M[2][2]*N[2][2] = 36
#效果1 #i => 0 1 2 j => 0 1 2 i动的慢 j 动的快
res = [M[i][j]*N[i][j] for i in range(3) for j in range(3)]
print(res)
#=> 效果2 [ [2,4,6] , [12,15,18], [28,32,36] ]
# [] [] []
'''
分析:
第一步遍历三个空列表
[[] for i in rang(3)]
第二步 空列表里面写一个推导式对于的元素
[M[i][j]*N[i][j] for j in rang(3)]
'''
res =[ [M[i][j]*N[i][j] for j in range(3)] for i in range(3)]
print(res) #[[2,4,6] [] []]
3.
二.集合推导式
例:
满足年龄在18到21,存款大于等于5000 小于等于5500的人,
开卡格式为:尊贵VIP卡老x(姓氏),否则开卡格式为:抠脚大汉卡老x(姓氏)
把开卡的种类统计出来
listvar = [
{"name":"王家辉","age":18,"money":10000},
{"name":"王水机","age":19,"money":5100},
{"name":"王鹏","age":20,"money":4800},
{"name":"李站","age":21,"money":2000},
{"name":"李小龙","age":180,"money":20}
]
#res = {'a':1,'b':2}
#for i in res:
# print(i)
setvar = set()
for i in listvar:
if 18<=i['age'] <=21 and 5000 <i['money'] <= 5500:
strvar = '尊贵VIP卡老' + i["name"][0]
setvar.add(strvar)
else:
strvar = '抠脚大汉卡老' + i['name'][0]
setvar.add(strvar)
print(setvar)
#真值 if 条件表达式 else 假值
#第一部分 for i in listvar
#第二部分 三目运算 : "尊贵VIP卡老" + i["name"][0] if 18 <= i['age']<=21 and 5000<=i['money']<=5500 else "抠脚大汉卡老" + i['name'][0]
res = {"尊贵VIP卡老" + i['name'][0] if 18 <= i['age'] <= 21 and 5000 <=i['money'] <=5000 else "抠脚大汉卡老" + i['name'][0] for i in listvar}
print(res)
三.字典推导式
1.enumerate
enumerate(iterable,[start=0])
功能: 枚举 ; 将所有引号和iterable中的值,一个个拿出来配对组成元组放入迭代器中
参数:
iterable : 可迭代性数据(常用:迭代器,容器类型数据,可迭代对象range)
start: 可以选择开始的索引号(默认从0开始索引)
返回值: 迭代器
listvar = ["one","two","three","four"]
it = enumerate(listvar)
from collections import Iterable,Iterator
print(isinstance(it,Iterator))
#(1)使用next进行调用
res = next(it)
print(res)
res = next(it)
print(res)
#(2) 使用for来调用
for i in it:
print(i)
#(3)用list 瞬间得到所有数据
it = enumerate(listvar)
lst = list(it)
print(lst) #[(0, 'one'), (1, 'two'), (2, 'three'), (3, 'four')]
#利用enumerate变成字典推导式
res = {a:b for a,b in enumerate(listvar)}
print(res)
#使用dict强转迭代器
res = dict(enumerate(listvar))
print(res)
2.zip
功能:将多个iterable中的值,一个一个拿出来配对组成元组放入迭代器中
iterable:可迭代性数据(常用:迭代器,容器类型数据,可迭代对象range )
返回:迭代器
#(1) zip自动配对,如果长度超出了,自动舍弃
lst1 = ["one","two","three","four"]
lst2 = ["英俊潇洒","疯牛踢躺","柔情似水","抠脚大汉",1,2,3,4]
it = zip(lst1,lst2)
print(isinstance(it,Iterator))
#使用for 搭配next进行调用
for i in range(3):
res = next(it)
print(res)
for i in it:
print(i)
#利用zip实现字典推导式
res = {a:b for a,b in zip(lst1,lst2)}
print(res)
#使用dict强转迭代器
res = dict(zip(lst1,lst2))
print(res)
#(2) 用两个列表,实现如下字典:
# 'xd':'熊大'
# 'xe':'熊二'
# 'gtq':'光头强'
dic1 = {'xd':"傻乎乎","xe":"呆呼呼","gtq":"光头"}
dic2 = {0:"熊大",1:"熊二",2:"光头强"}
lst_keys = dic1.keys()
#print(lst_keys)
#print(isinstance(lst_keys,Iterator))
#print(isinstance(lst_keys,Iterable))
lst_values = dic2.values()
print(lst_values)
#print(isinstance(lst_values,Iterable))
#print(isinstance(lst_values,Iterator))
it = zip(lst_keys,lst_values)
print(it)
#使用字典推导式实现
res = {a:b for a,b in it}
print(res)
#使用dict强转迭代器实现
it = zip(lst_keys,lst_values)
res = dict(it)
print(res)