Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
람다 함수
일반적으로 우리는 코드에서 def 키워드를 사용하여 함수를 정의하고 필요할 때마다 호출합니다.
def sum(a,b):
return a + b
a = 1
b = 2
c = sum(a,b)
print(c)
이제 함수를 정의하고 호출하는 대신, 파이썬의 람다 함수를 사용할 수 있습니다. 이는 함수가 사용되는 곳에서 바로 정의되는 인라인 함수입니다. 따라서 단일 사용을 위해 함수를 다른 곳에 선언하고 코드를 다시 보는 것이 필요하지 않습니다.
람다 함수는 이름을 필요로 하지 않기 때문에 익명 함수라고도 불립니다. 우리는 키워드 lambda를 사용하여 람다 함수를 정의합니다.
your_function_name = lambda inputs : output
따라서 이전의 sum 예제를 람다 함수를 사용하여 작성하면,
a = 1
b = 2
sum = lambda x,y : x + y
c = sum(a,b)
print(c)
여기에서 우리는 람다 함수를 변수 sum에 할당하고, 인수 a와 b를 제공할 때, 이는 일반 함수처럼 작동합니다.
Exercise
주어진 리스트에서 숫자가 홀수인지 확인하는 람다 함수를 사용하여 프로그램을 작성하십시오. 숫자가 홀수이면 "True"를 인쇄하고, 그렇지 않으면 "False"를 각 요소에 대해 인쇄합니다.
l = [2,4,7,3,14,19]
for i in l:
# your code here
l = [2,4,7,3,14,19]
for i in l:
# your code here
my_lambda = lambda x : (x % 2) == 1
print(my_lambda(i))
test_output_contains("False")
test_output_contains("False")
test_output_contains("True")
test_output_contains("True")
test_output_contains("False")
test_output_contains("True")
success_msg("Nice work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!