如何写好Python lambda函数?
当你需要完成一件小工作时,在本地环境中使用这个函数,可以让工作如此得心应手,它就是Lambda 函数。
lambda arguments: expression>>> integers = [(3, -3), (2, 3), (5, 1), (-4, 4)]>>> sorted(integers, key=lambda x: x[-1])[(3, -3), (5, 1), (2, 3), (-4, 4)]>>> sorted(integers, key=lambda x: return x[-1])...File "", line 1sorted(integers, key=lambda x: return x[-1])^SyntaxError: invalid syntax
>>> integers = [-4, 3, 7, -5, -2, 6]>>> sorted(integers, key=lambda x: abs(x))[-2, 3, -4, -5, 6, 7]>>> sorted(integers, key=abs)[-2, 3, -4, -5, 6, 7]>>> scores = [(93, 100), (92, 99), (95, 94)]>>> max(scores, key=lambda x: x[0] + x[1])(93, 100)>>> max(scores, key=sum)(93, 100)
>>> import pandas as pd>>> data = pd.Series([1, 2, 3, 4])>>> data.map(lambda x: x + 5)0 61 72 83 9dtype: int64>>> data + 50 61 72 83 9dtype: int64
>>> doubler = lambda x: 2 * x>>> doubler(5)10>>> doubler(7)14>>> type(doubler)<class 'function'>
>>> inversive0 = lambda x: 1 / x>>> inversive0(2)0.5>>> inversive0(0)Traceback (most recent call last):File "", line 1, in <module>File "", line 1, inZeroDivisionError: division by zero>>> def inversive1(x):... return 1 / x...>>> inversive1(2)0.5>>> inversive1(0)Traceback (most recent call last):File "", line 1, in <module>File "", line 2, in inversive1ZeroDivisionError: division by zero
>>> # 创建一个数字列表>>> numbers = [2, 1, 3, -3]>>> # 使用带有 lambda 函数的 map 函数>>> list(map(lambda x: x * x, numbers))[4, 1, 9, 9]>>> # 使用带有 lambda 函数的 filter 函数>>> list(filter(lambda x: x % 2, numbers))[1, 3, -3]
>>> # Use list comprehensions>>> [x * x for x in numbers][4, 1, 9, 9]>>> [x for x in numbers if x % 2][1, 3, -3]
本文来源:掘金社区。仅用于传递和分享更多信息,并不代表本平台赞同其观点和对其真实性负责,版权归原作者所有,如有侵权请联系我们删除。
-END- 推荐阅读:
10W字《R ggplot2可视化教程1.0》来了! 详解Python列表推导式|迭代器|生成器|匿名函数 Jupyter Notebook的16个超棒插件! 临床WGS/WES/Gene Panel/Single gene异同 一图胜千言,超形象图解NumPy教程! 那些神经网络可视化利器 R Graphics Cookbook中译教程
我的学习小圈子👉 加入
赞、在看就是最大的支持