Program Tip

인수에 대한 밑줄이있는 Python의 람다?

programtip 2020. 10. 29. 19:09
반응형

인수에 대한 밑줄이있는 Python의 람다?


다음 코드는 무엇을합니까?

a = lambda _:True

대화 형 프롬프트에서 읽고 테스트 한 내용에서 항상을 반환하는 함수 인 것 같습니다 True.

나는 이것을 올바르게 이해하고 있습니까? 밑줄 ( _)도 사용 된 이유를 이해하고 싶습니다 .


_변수 이름입니다. 시도 해봐. (이 변수 이름은 일반적으로 무시 된 변수의 이름입니다. 말하자면 자리 표시 자입니다.)

파이썬 :

>>> l = lambda _: True
>>> l()
<lambda>() missing 1 required positional argument: '_'

>>> l("foo")
True

따라서이 람다 는 하나의 인수가 필요합니다 . 항상을 반환하는 인수가없는 람다를 원하면 다음 True 같이하십시오.

>>> m = lambda: True
>>> m()
True

밑줄은 사용하지 않는 변수의 이름을 지정하는 Python 규칙입니다 (예 : 정적 분석 도구는이를 사용하지 않는 변수로보고하지 않음). 귀하의 경우에는 람다 인수가 사용되지 않지만 생성 된 객체는 항상을 반환하는 단일 인수 함수입니다 True. 따라서 람다는 수학의 상수 함수다소 유사합니다 .


관계없이 True를 반환하는 함수 인 것 같습니다.

예, True를 반환하는 함수 (또는 람다)입니다. 밑줄 보통 무시 변수에 대한 자리이며,이 경우에 불필요하다.

(거의 아무것도하지 않는) 이러한 함수의 사용 사례:

dd = collections.defaultdict(lambda: True)

defaultdict 의 인수로 사용 True하면 일반적인 기본값으로 사용할 수 있습니다 .


Lambda는 함수를 의미합니다. 위의 진술은 쓰기와 동일합니다

def f(_):
    return True

람다의 경우 변수가 있어야합니다. 그래서 당신은 _(마찬가지로 x, y..) 라는 변수를 전달합니다 .


밑줄 _은 유효한 식별자이며 여기서 변수 이름으로 사용됩니다. 항상 True함수에 전달 된 인수에 대해 반환 됩니다.

>>>a('123') 
True

다음은 문제의 코드 줄입니다.

a = lambda _:True

하나의 입력 매개 변수를 갖는 함수를 생성합니다 : _. 밑줄은 변수 이름의 다소 이상한 선택이지만 변수 이름 일뿐입니다. _람다 함수를 사용하지 않을 때도 어디서나 사용할 수 있습니다 . 예를 들어 대신 ....

my_var = 5
print(my_var)

다음과 같이 작성할 수 있습니다.

_ = 5
print(_)

하지만 _매개 변수 이름의 이름으로 x대신 사용 된 이유가 있었습니다 input. 우리는 잠시 후에 그것에 대해 알아볼 것입니다.

먼저 람다 키워드가와 유사 def하지만 구문이 다른 함수를 구성한다는 것을 알아야 합니다. 람다 함수의 정의는 다음 a = lambda _:True과 같이 작성합니다.

def a(_):
    return True

a입력 매개 변수로 명명 된 함수를 생성하고을 _반환합니다 True. 하나는 그냥 간단하게 쓸 수 있었다 a = lambda x:True으로, x대신 밑줄. 그러나 관례는 _해당 변수를 사용하지 않으려는 경우 변수 이름으로 사용하는 것입니다. 다음을 고려하세요:

for _ in range(1, 11):
    print('pear')

루프 인덱스는 루프 본문 내부에서 사용되지 않습니다. 우리는 단순히 루프가 지정된 횟수만큼 실행되기를 원합니다. winklerrr작성했습니다, "변수 이름 _입니다 [...]는 같은"던져 - 멀리 변수 "아무 소용이, 그냥 자리 표시 자."

이와 함께`람다 A = X : 참 입력 매개 변수 함수의 본문 내에서 사용되지 않는다. 입력 인수가있는 한 입력 인수가 무엇인지는 실제로 중요하지 않습니다. 해당 람다 함수의 작성자는 변수가 사용되지 않을 것임을 나타 내기 위해 _와 같은 대신 작성 했습니다 x.

람다 에는 인수가 있습니다. 그래서 쓰기

a(), 오류가 발생합니다.

인수가없는 람다를 원한다면 다음과 같이 작성하십시오.

 bar = lambda: True

Now calling bar(), with no args, will work just fine. A lambda which takes no arguments need not always return the same value:

import random
process_fruit = lambda : random.random()

The lambda function above is more complex that just a something which always returns the same constant.

One reason that programmers sometimes us the lambda keyword instead of def is for functions which are especially short and simple. Note that a lambda definition can usually fit all on one line, whereas, it is difficult to do the same with a def statement. Another reason to use lambda instead of def sf when the function will not be used again. If we don't want to call the function again later, then there is no need to give the function a name. For example consider the following code:

def apply_to_each(transform, in_container): out_container = list() for idx, item in enumerate(container, 0): out_container[idx] = transform(item) return out_container

Now we make the following call:

squares  = apply_to_each(lambda x: x**2 range(0, 101))

Notice that lambda x: x**2 is not given a label. This is because we probably won't call it again later, it was just something short and simple we needed temporarily.

The fact that lambda functions need not be given a name is the source of another name to describe them: "anonymous functions."

Also note that lambda-statements are like a function-call in that they return a reference to the function they create. The following is illegal:

apply_to_each(def foo(x): x**2 ,  range(0, 101))

Whereas, apply_to_each(lambda x: x**2 range(0, 101)) is just fine.

So, we use lambda instead of def and _ instead of a long variable name when we want something short, sweet and probably won't want use again later.

참고URL : https://stackoverflow.com/questions/29767310/pythons-lambda-with-underscore-for-an-argument

반응형