代码笔记20 python中的max与lambda函数

1

  就直接上我的代码吧,主要是对max函数与lambda函数的学习。
  其中max函数的说明[1]
  是一个最大值函数,返回输入数据(可迭代的,如列表字典等等)的最大值,同时可以通过key属性(输入为函数),输出需要的数据最大值
  lambda函数的说明[2]
  是一种轻量级的函数定义方法,刚好可以巧妙地用在max函数中key属性的定义

2

第一种

if __name__ == "__main__":
    shape1 = [128, 15, 50]
    shape2 = [512, 30, 40]
    shape3 = [1024, 20, 30]
    shapes = [shape1, shape2, shape3]
    k = max(shapes)
    print(k)
>>[1024, 20, 30]

第二种,加入key属性。使用lambda函数,定义为list的第二个数字

if __name__ == "__main__":
    shape1 = [128, 15, 50]
    shape2 = [512, 30, 40]
    shape3 = [1024, 20, 30]
    shapes = [shape1, shape2, shape3]
    k = max(shapes,key = lambda x:x[1])
    print(k)
>>[512, 30, 40]

第三种,加入key属性。使用lambda函数,定义为list的第三个数字

if __name__ == "__main__":
    shape1 = [128, 15, 50]
    shape2 = [512, 30, 40]
    shape3 = [1024, 20, 30]
    shapes = [shape1, shape2, shape3]
    k = max(shapes,key = lambda x:x[2])
    print(k)
>>[128, 15, 50]

Refrences

[1] https://www.runoob.com/python/func-number-max.html
[2] https://www.runoob.com/python/python-functions.html

posted @ 2022-06-25 19:28  The1912  阅读(307)  评论(0编辑  收藏  举报