程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] lambda expression

編輯:Python

lambda expression

Use scenarios :

Function has a return value , And only one sentence of code lambda simplify !
There is the ultimate simplification at the end of the text , If you are interested, you can understand !

grammar :

lambda parameter list : expression
notes : Parameter list is optional

example :

1. With no arguments

fn = lambda: 100
print(fn())
# output 100
print(fn)
#output Function address 

2. With parameters

fn = lambda a, b: a + b
print(fn(2, 3))
# output 5

3. Default parameters

fn = lambda a, b, c=100: a + b + c
print(fn(2, 4, 4))
# output 10
print(fn(2, 4))
# output 106

4. Use for judgment ( Used with the trinocular operator )

fn = lambda a, b: a if a > b else b
print(fn(4, 10))
# output 10

5. For unpacking

fn = lambda *args: args
print(fn(10, 20, 30))
# output (10, 20, 30)

6. The ultimate use
One line fix 1-100 Cumulative sum :

import functools
print(functools.reduce(lambda a, b: a + b, range(1, 101)))
# 5050

One line fix 1-100 Even and :

import functools
print(functools.reduce(lambda a, b: a + b, list(filter((lambda x: x % 2 == 0), range(101)))))
# 2550

It's over , Other usages are not described here .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved