Python3 lambda

匿名函数的语法、与 def 的取舍、配合 map/filter/sorted 使用及常见陷阱。

Intermediate
Key Pointslambda 只能写一个表达式且自动返回其结果;适合一次性小回调,复杂逻辑仍应用 def。

lambda 语法

lambda args: expr creates an anonymous function whose value is the expression — no return needed. It is still a function object: assignable and immediately callable.

Python
f = lambda x: x + 1
print(f(1), type(f).__name__)

print((lambda x, y: x * y)(3, 4))
print((lambda: "no args")())

add = lambda *args: sum(args)
print(add(1, 2, 3))
Output
2 function
12
no args
6

lambda 与 def 的对比

def allows multiple statements, docstrings and a real name in debuggers; a lambda is a single anonymous expression. Use a lambda only when the body is one expression and the function is throwaway.

Python
def square_def(x):
    """返回平方"""
    return x * x

square_lambda = lambda x: x * x

print(square_def(3), square_lambda(3))
print(square_def.__name__, square_lambda.__name__)
print(bool(square_def.__doc__), square_lambda.__doc__)
Output
9 9
square_def <lambda>
True None

配合 map/filter/sorted 使用

Lambdas shine as throwaway rules for higher-order functions: sorted(key=...), map for transforms, filter for selection, max/min(key=...) for extremes by field.

Python
rows = [('b', 2), ('a', 3), ('c', 1)]

print(sorted(rows, key=lambda r: r[1]))
print(sorted(rows, key=lambda r: r[0], reverse=True))
print(list(map(lambda r: r[0].upper(), rows)))
print(list(filter(lambda r: r[1] > 1, rows)))
print(max(rows, key=lambda r: r[1]))
Output
[('c', 1), ('b', 2), ('a', 3)]
[('c', 1), ('b', 2), ('a', 3)]
['B', 'A', 'C']
[('b', 2), ('a', 3)]
('a', 3)

闭包与默认参数陷阱

A lambda captures the *variable*, not the value. Lambdas created in a loop share the loop variable and all see its final value — bind the current value with a default argument like x=x.

Python
fs = [lambda: i for i in range(3)]
print([f() for f in fs])

fs2 = [lambda i=i: i for i in range(3)]
print([f() for f in fs2])

def make_adder(n):
    return lambda x: x + n

add5 = make_adder(5)
print(add5(10), add5(0))
Output
[2, 2, 2]
[0, 1, 2]
15 5
The same trap applies to def defaults: def f(x, acc=[]) shares one list across calls. Use acc=None and create it inside.

Friends & Partners