4.7.5. Lambda Expressions
람다 표현식
Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b
. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
크기가 작은 무명의 함수들은 lambda 키워드와 함께 만들어지기도 합니다. Lambda 라는 함수는 그 안에 있는 두 개의 인수를 더하여 값을 내어놓습니다 : lambda a, b : a+b
. Lambda 함수는 함수 객체가 요구되는 어떤 곳이든 사용할 수 있습니다. lambda 함수들은 단 하나의 표현식에 의해 문법적으로 제어되는데, 일반적인 함수 정의를 위한 달달한 설탕같은 문법이라고 보면 됩니다. 중첩된 함수 정의처럼, lambda 함수는 포함된 범위내의 변수를 사용할 수 있습니다.
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:
위의 예시는 어떤 함수의 답을 알기 위해 람다 표현식을 사용했습니다. 답을 알려주는 기능 외에 소규모 함수를 인수로 전달하고 있습니다.
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]