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?

More than 3 years have passed since last update.

Python 無名関数

Posted at

無名関数とは

・無名関数(匿名関数)とは、名前のない関数のことです。
・主に関数の名前をつける必要がない簡単な処理で終わるような関数を作る場合に使用します。
・無名関数を作るには、lambda(ラムダ式)という書式を用います。


書式

変数 = lambda 引数1, 引数2 : 式

通常の書き方

def func(引数1, 引数2):
    return 返り値

下記の2つの分は同じ処理、同じ結果となります。

def double(n):
    return n * 2

lambda n: n * 2

下記は同じ結果となります。

def double(n):
    return n * 2

lambda_ver = lambda n: n * 2

print(double(2) == lambda_ver(2))
# True

lambda式は、sorted(), map(), filter()などの関数に渡す無名関数として利用されることがあります。

a = [1, 2, 3]
print map(lambda x: x ** 2, a)
# [1, 4, 9]

引数をつけずに実行することも可能です。

lambda: random.rand()

ラムダ式では複数行にまたがる文を使うことはできませんが、if文に相当する三項演算子は使用可能です。

get_odd_even = lambda x: 'even' if x % 2 == 0 else 'odd'

print(get_odd_even(3))
# odd

print(get_odd_even(4))
# even

PEP8ではlambda式には名前を付けないのが推奨

・これまでの例のようにラムダ式に名前を割り当てる(ラムダ式を変数に代入する)とPythonのコーディング規約PEP8の自動チェックツールなどでWarningが出ることがあります。
・ラムダ式は呼び出し可能なオブジェクトを引数で渡すときなどに名前を付けずに使うためのもので、名前を付けて関数を定義する場合はdefを使うべきとあります。
PEP8-- Style Guide for Python Code | Python.org

Do not assign a lambda expression, use a def (E731)

以上、無名関数について簡単に解説しました。

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?