Python에서 lambdas 유용한가요?

LONGNEW·2021년 1월 12일
0

StackOverFlaw

목록 보기
15/16

https://stackoverflow.com/questions/890128/why-are-python-lambdas-useful

Q. Why are Python lambdas useful?
Q. Python에서 lamdas 유용한가요?


Are you talking about lambda functions? Like
lambda 말씀 하시는게 이런 건가요??

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.
Python에선 함수를 다른 함수에 전달하는 함수형 프로그래밍을 지원 합니다.

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.
리스트 안의 아이템 중 3의 배수들을 모아서 mult3에 저장합니다.
This is shorter (and, one could argue, clearer) than
이것은 아래 처럼 하는 것보다 코드의 길이가 짧습니다.(깔끔하기도 하고요.)

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:
물론, 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 many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out.
그러나, list comprehension을 이용할 수 없는 특정한 상황에서 lambda 함수를 쓰는 것이 가장 코드를 구성하기 짧은 방법일 수 있습니다.

  • Returning a function from another function
>>> def transform(n):
...     return lambda x: x + n
...
>>> f = transform(3)
>>> f(4)
7

This is often used to create function wrappers, such as Python's decorators.
이러한 구성은 Python의 데코레이터를 만들 때 자주 사용 됩니다.

  • Combining elements of an iterable sequence with reduce()
>>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])
'1, 2, 3, 4, 5, 6, 7, 8, 9'
  • Sorting by an alternate key
>>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
[5, 4, 6, 3, 7, 2, 8, 1, 9]

I use lambda functions on a regular basis.
lambda 함수를 평소에도 사용합니다.
It took me a while to get used to them, but eventually I came to understand that they're a very valuable part of the language.
손에 익기 까지에는 시간이 좀 걸렸는데, 이해하고 나서부터는 프로그래밍 언어에서 중요한 부분이 되었습니다.

0개의 댓글