如何写好Python的Lambda函数?
恋习Python
共 3535字,需浏览 8分钟
·
2023-03-10 21:29
lambda arguments: expression
>>> integers = [(3, -3), (2, 3), (5, 1), (-4, 4)]
lambda x: x[-1]) sorted(integers, key=
[(3, -3), (5, 1), (2, 3), (-4, 4)]
lambda x: return x[-1]) sorted(integers, key=
File "", line 1
sorted(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 6
1 7
2 8
3 9
dtype: int64
>>> data + 5
0 6
1 7
2 8
3 9
dtype: int64
>>> doubler = lambda x: 2 * x
>>> doubler(5)
10
>>> doubler(7)
14
>>> type(doubler)
<class 'function'>
0 = lambda x: 1 / x > inversive
0(2) > inversive
0.5
0(0) > inversive
Traceback (most recent call last):
File "", line 1, in <module>
File "", line 1, in
ZeroDivisionError: division by zero
def inversive1(x): >
... return 1 / x
...
2) > inversive1(
0.5
0) > inversive1(
Traceback (most recent call last):
File "", line 1, in <module>
File "", line 2, in inversive1
ZeroDivisionError: 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]
评论