# python 之 推导式

21 篇文章 0 订阅

### 推导式

语法: val for val in Iterable

[val for val in Iterable]  列表推导式
{val for val in Iterable}  集合推导式
{k:v for k,v in Iterable}  字典推导式


例如: 一个列表里需要100条数据
lst= [i for i in range(1,101)]
print(lst)


(1) 单循环推导式

例:[1,2,3,4,5]  =>[3,6,9,12,15]
# 常规写法
lst = [1,2,3,4,5]
lst_new=[]
for i in lst:
res= i*3
lst_new.append(res)
print(lst_new)
# 推导式改写
lst=[i*3 for i in lst]
print(lst)


(2)带有判断条件的单循环推导式(只能是单项分支,接在for后面)

例:[1,2,3,4,5,6,7,8]  =>找出奇数
#常规写法
lst=[1,2,3,4,5,6,7,8]
lst_new=[]
for i in lst:
if i %2 ==1:
lst_new.append(i)
print(lst_new)
# 推导式改写
lst=[i for i in lst if i %2 ==1]
print(lst)


(3)双循环推导式

例: lst1 = ["李博伦","高云峰","孙致和","葛龙"]
lst2 = ["李亚","刘彩霞","刘子豪","刘昕"]
# "谁"❤"谁"
# 常规写法
lst_new= []
for i in lst1:
for j in lst2:
strvar = i+"❤"+j
lst_new.append(strvar)
print(lst_new)
# 推导式改写
lst=[i+"❤"+j for i in lst1 for j in lst2]
print(lst)


(4)带有判断条件的多循环推导式

#常规写法
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)
推导式改写
lst=[i + "❤" + j for i in lst1 for j in lst2 if lst1.index(i) ==lst2.index(j)]
print(lst)


案例:
满足年龄在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":18,"money":20}
]
# 常规写法
setvar = set()
for i in listvar:
if 18 <= i["age"] <= 21 and  5000 <= i["money"] <= 5500:
res = "尊贵VIP卡老" + i["name"][0]
else:
res = "抠脚大汉卡老" + i["name"][0]
print(setvar)
# 改写成集合推导式
# {三元运算符 + 推导式}
setvar = { "尊贵VIP卡老" + i["name"][0] if 18 <= i["age"] <= 21 and  5000 <= i["money"] <= 5500 else "抠脚大汉卡老" + i["name"][0] for i in listvar }
print(setvar)


enumerate

start: 可以选择开始的索引号(默认从0开始索引)

例:lst = ["你好","今天","明天","再见"]
it= enumerate(lst)
for + next 调用
for i in range(4):
print(next(it))
# list调用
"""start可以指定开始值,默认是0"""
it = enumerate(lst,start=1)
print(list(it))
# enumerate 形成字典推导式 变成字典
dic = { k:v for k,v in enumerate(lst,start=1) }
print(dic)
# dict 强制变成字典
dic = dict(enumerate(lst,start=1))
print(dic)


zip

iterable: 可迭代性数据 (常用:迭代器,容器类型数据,可迭代对象 range)

基本使用
lst1 = ["张三","李四","王金","小明"]
lst2 = ["今天","明天","昨天","后天"]
lst3=["苹果","桃子","西瓜"]
it = zip(lst1,lst2,lst3)
print(list(it))
# zip 形成字典推导式 变成字典
lst2 = ["今天","明天","昨天","后天"]
lst3=["苹果","桃子","西瓜"]
dic = { k:v for k,v in zip(lst1,lst2) }
print(dic)
# dict 强制变成字典
dic = dict(zip(lst1,lst2))
print(dic)

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
01-21 2166
07-15 1800
09-16
06-28 701
03-22 8219
03-15 342
03-26 1879

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。