程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(1)

python 学习笔记2 匿名函数

发布于2020-01-20 18:26     阅读(954)     评论(0)     点赞(21)     收藏(2)


# 匿名函数  lambda a,b : a+b
# a.j.
from functools import reduce

students = [{'name': '张三', 'age': 18, 'height': 188},
{'name': '李四', 'age': 17, 'height': 178},
{'name': '王五', 'age': 19, 'height': 186}]
# 按height排序 reverse=True 反向
resultSorted = sorted(students, key=lambda x: x['height'], reverse=True)
print('resultSorted: {}'.format(list(resultSorted)))

# 求age最大
resultMax = max(students, key=lambda x: x['age'])
print('resultMax: {}'.format(resultMax))

# 求heght最小
resultMin = min(students, key=lambda x: x['height'])
print('resultMin: {}'.format(resultMin))

# 筛选age大于17的字典
resultFilter = filter(lambda x: x['age'] > 17, students)
print('resultFilter: {}'.format(list(resultFilter)))

# 每个age元素都+2
resultMap = map(lambda x: x['age'] + 2, students)
print('resultMap: {}'.format(list(resultMap)))

# 元组所有元素求和
tupleReduce = (1, 2, 3, 4, 5, 6, 7, 8, 9)
resultReduce = reduce(lambda a, b: a + b, tupleReduce)
print('resultReduce: {}'.format(resultReduce))

# 各个结果
'''
resultSorted: [
  {'name': '张三', 'age': 18, 'height': 188},
  {'name': '王五', 'age': 19, 'height': 186},
  {'name': '李四', 'age': 17, 'height': 178}]

resultMax:{'name': '王五', 'age': 19, 'height': 186}
resultMin:{'name': '李四', 'age': 17, 'height': 178}
resultFilter: [
  {'name': '张三', 'age': 18, 'height': 188},
  {'name': '王五', 'age': 19, 'height': 186}]

resultMap: [20, 19, 21]

resultReduce: 45
'''


所属网站分类: 技术文章 > 博客

作者:短发越来越短

链接:https://www.pythonheidong.com/blog/article/229181/69187f1ef928e4eaa10b/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

21 0
收藏该文
已收藏

评论内容:(最多支持255个字符)