1、匿名函數:lambda¶
In [1]:
f=lambda x,y,z:x+y+z
f(2,3,4)
Out[1]:
9
In [2]:
L=[lambda x:x**2,
lambda x: x**3,
lambda x:x**4]
for f in L:
print(f(2))
4
8
16
In [3]:
import sys
showall=lambda x:[sys.stdout.write(line) for line in x] #在lambda中進行print
t=showall(('bright\n', 'side\n', 'of\n', 'life\n'))
bright
side
of
life
2、在序列重新對應函數:map¶
In [4]:
counters=[1,2,3,4]
def inc(x):return x+10
map(inc,counters)
#說明:map函數對一個序列對象中的每一個元素應用被傳入的函數,並且返回一個包含了所有函數調用結果的一個列表
Out[4]:
[11, 12, 13, 14]
In [5]:
pow(2,3)
Out[5]:
8
In [6]:
map(pow,[1,2,3],[2,3,4])
Out[6]:
[1, 8, 81]
3、函數式編程工具:filter和reduce¶
In [7]:
range(-5,5)
Out[7]:
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
In [8]:
filter((lambda x:x>0), range(-5,5))
Out[8]:
[1, 2, 3, 4]
In [9]:
reduce((lambda x,y:x+y),[1,2,3,4])
Out[9]:
10
In [10]:
reduce((lambda x,y:x*y),[1,2,3,4])
Out[10]:
24
In [11]:
reduce((lambda x,y:x*y),[1,2,3,4])
Out[11]:
24
In [ ]:
4、python3的reduce及如何查看python版本資訊¶
In [1]:
import platform
In [2]:
platform.python_version()
Out[2]:
'3.5.2'
In [3]:
from functools import reduce
In [4]:
reduce((lambda x,y:x+y),[1,2,3,4])
Out[4]:
10
In [5]:
import sys
print(sys.version)
3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul 5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]