0
0

python lambda式

Posted at

lambda [引数] : [処理内容] で関数を記述できる。

Example

def sum(a,b):
    return a + b

これをlambdaで書くと、

>>>sum = lambda a,b: a + b
>>>sum(1,2)
3

関数を引数として渡す場合なんかに簡潔に記載できる

#lambdaを使わない場合
pairs = [('three',3),('two',2),('four',4),('five',5),('one',1)]
def pair(item):
    return item[1]
pairs.sort(key=pair)
pairs#[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
#lambdaを使う場合
pairs = [('three',3),('two',2),('four',4),('five',5),('one',1)]
pairs.sort(key=lambda pair:pair[1])
pairs#[('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
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