[Python] lambda式について

2015年8月10日

リスト内包表記をまとめたいがためだけの回。
他のサイト様を見ていただいた方がいいかも。。。

[amazonjs asin="B009Z30HPG" locale="JP" title="Dive Into Python 3 日本語版"]

lambda式とは無名関数を作成するときに使うもの。

通常、pythonでは関数を作成するときには def を使う。
[shell title="defを使った関数"]
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
> def sum(x, y, z):
… return x + y + z

> sum(1, 2, 3)
6
[/shell]

これをlambda式では以下のように書く。

[shell title="lambdaを使った関数"]
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
> sum = lambda x, y, z: x + y + z
> sum(1, 2, 3)
6
[/shell]

使い方は以下のように書く。

[shell title="lambda式"]
lambda 引数1 引数2 引数3 …. : 処理
[/shell]

defと同じように、引数のデフォルト値も指定できる。

defの場合は

[shell title="defで引数にデフォルトを指定"]
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
> def sum(x, y=2, z=3):
… return x + y + z

> sum(1)
6
[/shell]

lambda式の場合も同様に、

[shell]
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
> sum = lambda x, y=2, z=3: x + y + z
> sum(1)
6
[/shell]

lambda式の応用例は次回のリスト内包表記で。