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)]