首页 > 其他 > 详细

lambda的几个应用

时间:2020-07-10 19:47:42      阅读:66      评论:0      收藏:0      [点我收藏+]

一、与sort

按分数排列student中的元素

students = [
{‘name‘: ‘Lee‘, ‘score‘: 98, ‘height‘: 180},
{‘name‘: ‘Jurry‘, ‘score‘: 66, ‘height‘: 168},
{‘name‘: ‘Hurry‘, ‘score‘: 80, ‘height‘: 172},
{‘name‘: ‘Nicy‘, ‘score‘: 78, ‘height‘: 183},
{‘name‘: ‘Mike‘, ‘score‘: 88, ‘height‘: 190},
]

students.sort(key=lambda ele: ele[‘score‘])
print(students)

输出

[{‘name‘: ‘Jurry‘, ‘score‘: 66, ‘height‘: 168},
{‘name‘: ‘Nicy‘, ‘score‘: 78, ‘height‘: 183},
{‘name‘: ‘Hurry‘, ‘score‘: 80, ‘height‘: 172},
{‘name‘: ‘Mike‘, ‘score‘: 88, ‘height‘: 190}, 
{‘name‘: ‘Lee‘, ‘score‘: 98, ‘height‘: 180}]

二、与filter

打印大于18的数

ages = [12, 23, 20, 30, 17, 22, 18]

x = filter(lambda ele: ele > 18, ages)

for a in x:
    print(a)

输出:

23
20
30
22

三、与map

元素都加上2

ages = [12, 23, 20, 30, 17, 22, 18]

x = map(lambda ele: ele + 2, ages)

for a in x:
    print(a)

输出:

14
25
22
32
19
24
20

四、与reduce

输出总得分

from functools import reduce

socres = [100, 89, 76, 87]

result = reduce(lambda x, y: x + y, socres)
print(result)  # 352

lambda的几个应用

原文:https://www.cnblogs.com/ychdzx/p/13280165.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!