Python | Lambda和map()与示例
该map()函数用于将函数应用于可迭代集合的所有项目,如列表,元组等,并在执行所应用函数中定义的功能后返回结果列表。
示例
给定温度列表,我们必须转换1)摄氏温度的所有值和2)华氏度的所有值-map()与lambda一起使用。
1)方法1:使用常规方法
#函数定义转换温度从c到f
def ctof(c):
f=9/5*c+32
return f
#函数定义转换温度从f到c
def ftoc(f):
c=5/9*(f-32)
return c
#值列表
temp=[12,45,6,78,5,26,67]
print("Orignal Data : ",temp)
#列出磁偏角以存储温度。在C
cel=[]
for t in temp:
x=ftoc(t)
cel.append(x)
print("Celcuis Data : ",cel)
#列出磁偏角以存储温度。在F
far=[]
for t in temp:
x=ctof(t)
far.append(x)
print("Farenhiet Data : ",far)输出结果
Orignal Data : [12, 45, 6, 78, 5, 26, 67] Celcuis Data : [-11.11111111111111, 7.222222222222222, -14.444444444444445, 25.555555555555557, -15.0, -3.3333333333333335, 19.444444444444446] Farenhiet Data : [53.6, 113.0, 42.8, 172.4, 41.0, 78.80000000000001, 152.60000000000002]
2)方法2:map()与lambda一起使用
#值列表
temp=[12,45,6,78,5,26,67]
print("Orignal Data : ",temp)
#使用map和lambda将值转换为cel
cel=list(map(lambda f:5/9*(f-32),temp))
print("Celcuis Data : ",cel)
#使用map和lambda将值转换为far
far=list(map(lambda c:9/5*c+32,temp))
print("Farenhiet Data : ",far)输出结果
Orignal Data : [12, 45, 6, 78, 5, 26, 67] Celcuis Data : [-11.11111111111111, 7.222222222222222, -14.444444444444445, 25.555555555555557, -15.0, -3.3333333333333335, 19.444444444444446] Farenhiet Data : [53.6, 113.0, 42.8, 172.4, 41.0, 78.80000000000001, 152.60000000000002]
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语