0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】lambda関数

Posted at

lambda関数

lambdaは、Pythonで無名関数(名前のない関数)を定義するためのキーワードです。lambda関数は、通常の関数と同様に引数を受け取り、式を評価して結果を返しますが、defを使って関数を定義するよりも簡潔に書くことができます。

基本的な構文

lambda arguments: expression

arguments: 関数が受け取る引数(カンマで区切ることができます)。
expression: 引数を使って評価される式。この式の結果が関数の戻り値になります。

例1: 単純なlambda関数

# 2つの数を足す無名関数
add = lambda x, y: x + y
print(add(3, 5))  # 出力: 8

例2: mapと組み合わせる

lambda関数は、mapやfilter、sortedなどの関数と組み合わせて使うことがよくあります。

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared)  # 出力: [1, 4, 9, 16, 25]

例3: filterと組み合わせる

filter関数と組み合わせて、条件に合う要素を抽出することもできます。

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # 出力: [2, 4]

例4: sortedと組み合わせる

sorted関数を使って、カスタムのソートを行うこともできます。

points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda point: point[1])  # y座標でソート
print(sorted_points)  # 出力: [(5, 0), (3, 1), (1, 2)]

注意点

lambda関数は、1つの式しか持つことができません。複雑な処理を行いたい場合は、通常のdefを使って関数を定義する方が良いでしょう。
可読性を考慮して、lambda関数は短くシンプルな処理に使うのが一般的です。
lambdaは、簡潔に関数を定義できる便利な機能です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?