본문 바로가기

프로그래밍/Python

[번역|StackOverflow] 파이썬 람다 - 왜써? / Python Lambda - why?

반응형
Are you talking about lambda functions? Like

람다 함수를 말하는 건가요? 이런 것?


f = lambda x: x**2 + 2*x - 5


Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:


이거 진짜 좋아요. 파이썬은 다른 함수에 함수를 넘길 수 있는 함수형 프로그래밍 스타일을 지원해요. 예를 들면 :


mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])


sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than


이 문장으로 mult3은 [3, 6, 9]가 됩니다. 원래 리스트 중 3의 배수인 원소들이죠. 이건 다음 문장보다 간결합니다.

def filterfunc(x):

    return x % 3 == 0

mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])


Of course, in this particular case, you could do the same thing as a list comprehension:


물론, 이 특수한 경우에는, 같은 짓을 아래와 같이 리스트 기능으로 할 수 있겠죠.:


mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]


(or even as range(3,10,3)) but there are other cases, like constructing functions as return values from other functions, where you can't use a list comprehension and a lambda function may be the shortest way to write something out. Like


(아니면 아예 range(3, 10, 3)으로도) 그렇지만, 다른 함수의 반환값으로 함수를 만들어 주는 것 같은 경우도 있을 수 있고, 이럴 때에는 람다 함수가 아마 그짓을 하는 가장 간단한 방법일 거예요. 예를 들면 이렇죠.:


def transform(n):

    return lambda x: x + n

f = transform(3)

f(4) # is 7


I use lambda functions on a regular basis. It took a while to get used to them but once I did I'm glad Python has them ;-)

전 람다 함수를 일상적으로 사용하고 있습니다. 익숙해 지는 데 시간이 걸렸지만, 한번 익숙해지니 파이썬이 람다를 지원하는 게 고맙군요.


http://stackoverflow.com/questions/890128/python-lambda-why

728x90