因为本文参考的文章较多,csdn无法在原文链接处填写多个链接,故此处仅填写一个链接,将所有参考文章的链接全部放在了文章最后。
1、lambda()
lambda()是Python里的匿名函数,其语法如下:
lambda [arg1[, arg2, … argN]]: expression
下面是个1+2=3的例子
>>> fun = lambda x,y:x+y
>>> fun(1,2)
3
>>> (lambda x,y:x+y)(1,2)
3
2、filter()
filter的语法形式如下:
filter(function, sequence):
对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:
下面是例子:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def f(x): return x != ‘a’
>>> filter(f, “abcdef”)
‘bcdef’
3、map()
map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:
>>> def cube(x): return xxx
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x) : return x + x
…
>>> map(cube , “abcde”)
[‘aa’, ‘bb’, ‘cc’, ‘dd’, ‘ee’]
另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:
>>> def add(x, y): return x+y
>>> map(add, range(8), range(8))
[0, 2, 4, 6, 8, 10, 12, 14]
4、reduce()
reduce(function, sequence, starting_value):
对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用.
例如可以用来对List求和:
>>> def add(x,y): return x + y
>>> reduce(add, range(1, 11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> reduce(add, range(1, 11), 20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)
5、综合例子
下面是两个综合利用以上四个函数的例子:
例子1:计算5!+4!+3!+2!+1!
a=[5,4,3,2,1]
def fun(x):
result = 1
while x >= 1:
result = result * x
x = x - 1
return result
print reduce(lambda x,y:x+y, map(fun,a))
例子2:将100以内的质数挑选出来
import math
def isPrime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
print filter(isPrime,range(1,100))
6.map和reduce的区别
①从参数方面来讲:
- map()函数:
map()包含两个参数,第一个参数是一个函数,第二个是序列(列表或元组)。其中,函数(即map的第一个参数位置的函数)可以接收一个或多个参数. - reduce()函数:
reduce() 第一个参数是函数,第二个是 序列(列表或元组)。但是,其函数(第一个参数位置的函数))必须接收两个参数。
②从对传进去的数值作用来讲:
- map()函数:
map()是将传入的函数依次作用到序列的每个元素,每个元素都是独自被函数“作用”一次;(请看下面的栗子) - reduce()函数:
reduce()是将传人的函数作用在序列的第一个元素得到结果后,把这个结果继续与下一个元素作用(累积计算),最终结果是所有的元素相互作用的结果。(请看下面的栗子)
举个栗子:
- map()函数:
# 传入一个参数
def one_p(x):
return x * x
print 'map1.1:', map(one_p, range(1, 5))
#结果:map1.1: [1, 4, 9, 16]
print 'map1.2:', map(one_p, [1, 2, 3, 4, 5, 6])
#结果:map1.2: [1, 4, 9, 16, 25, 36]
# 传入多个参数
a = [1, 2, 3, 4, 5]
b = [1, 1, 6, 2, 3]
c = [1, 2, 3, 4, 5]
s = map(lambda (x, y, z): x * y * z, zip(a, b, c))
print 'map2:', s
#结果:map2: [1, 4, 54, 32, 75]
- reduce()函数:
r1 = reduce(lambda x, y: x * y, (2, 2, 6, 2)) #运算过程:(((2*2)*6)*2)
r2 = reduce(lambda x, y: x * y, (2, 2, 6), 2) #<span style="font-family: Arial, Helvetica, sans-serif;">运算过程:(((2*2)*6)*2)</span>
print 'r1:', r1 # 结果:r1: 48
print 'r2:', r2 # 结果:r2: 48
参考:
- Zhu_Julian,CSDN, https://blog.csdn.net/dbanote/article/details/8912250
- code_better,CSDN, https://blog.csdn.net/code_better/article/details/52995199