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)
関数をどこかに定義して呼び出す代わりに、Pythonのlambda関数を使用できます。これは、使用する同じ場所にインラインで定義される関数です。これにより、一度だけ使用するためにどこかに関数を宣言し、コードを再訪する必要がありません。
名前を持つ必要がないため、匿名関数とも呼ばれます。lambdaキーワードを使用してlambda関数を定義します。
your_function_name = lambda inputs : output
上記のsumの例をlambda関数を使って書くと、
a = 1
b = 2
sum = lambda x,y : x + y
c = sum(a,b)
print(c)
ここでは、lambda関数を変数sumに代入し、引数、つまりaとbを与えると、通常の関数のように機能します。
Exercise
与えられたリスト内の数が奇数であるかどうかをチェックするために、lambda関数を使用してプログラムを書いてください。数が奇数なら「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!