如何写好Python的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)]
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[] + 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)
6
1 7
2 8
3 9
dtype: int64
>>> data + 5
6
1 7
2 8
3 9
dtype: int64
>>> doubler = lambda x: 2 * x
>>> doubler(5)
10
>>> doubler(7)
14
>>> type(doubler)
<class 'function'>
> inversive = lambda x: 1 / x
2) > inversive(
.5
> 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(
.5
> 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]
相关文章