内置函数_map()、reduce()、filter()
map()、reduce()、filter()
-
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(map(str,range(5))) # 把列表中的元素转换为字符串
['0', '1', '2', '3', '4']
>>> list(map(float,range(5)))
[0.0, 1.0, 2.0, 3.0, 4.0]
>>> def add5(v): # 单参数函数
... return v + 5
...
>>> list(map(add5,range(10)))
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> def add(x,y): # 2个参数函数
... return x + y
...
>>> list(map(add,range(5),range(5,10)))
[5, 7, 9, 11, 13]
>>> list(map(lambda x,y: x+y,range(5),range(5,10)))
[5, 7, 9, 11, 13]
>>> def myMap(lst,value): # 自定义函数
... return map(lambda item: item+value,lst)
...
>>> list(myMap(range(5),5))
[5, 6, 7, 8, 9]
>>> list(myMap(range(5),8))
[8, 9, 10, 11, 12]
>>> def myMap(iterable,op,value): #实现序列的四则运算
... if op not in '+-*/':
... return 'Error operator'
... func = lambda i:eval(repr(i)+op+repr(value))... return map(func,iterable)...>>> list(myMap(range(5),'+',5))[5, 6, 7, 8, 9]>>> list(myMap(range(5),'-',5))[-5, -4, -3, -2, -1]>>> list(myMap(range(5),'*',5))[0, 5, 10, 15, 20]>>> list(myMap(range(5),'/',5))[0.0, 0.2, 0.4, 0.6, 0.8]>>> list(myMap(range(5),'%',5))['E', 'r', 'r', 'o', 'r', ' ', 'o', 'p', 'e', 'r', 'a', 't', 'o', 'r']>>> myMap(range(5),'%',5)'Error operator'>>> import random>>> x = random.randint(1,1e30)>>> x970963733240482734030028347859>>> list(map(int,str(x)))[9, 7, 0, 9, 6, 3, 7, 3, 3, 2, 4, 0, 4, 8, 2, 7, 3, 4, 0, 3, 0, 0, 2, 8, 3, 4, 7, 8, 5, 9] -
标准库functools中的函数reduce()可以将一个接收2个参数的函数以迭代累计的方式从左到右依次作用到一个序列或迭代器对象的所有元素上,并且允许指定一个初始的值。例如,reduce(lambda x, y: x+y, [1,2,3,4,5])计算过程为((((1+2)+3)+4)+5)
>>> from functools import reduce
>>> seq=list(range(1,10))
>>> seq
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> reduce(add,seq)
45
>>> reduce(lambda x,y:x+y,seq)
45
>>> import operator
>>> operator.add(3,5)
8
>>> reduce(operator.add,seq)
45
>>> reduce(operator.add,seq,5) # 指定累加的初始值为5
50
>>> reduce(operator.mul,seq)
362880
>>> reduce(operator.mul,range(1,6)) # 5的阶乘
120
>>> reduce(operator.add,map(str,seq))
'123456789'
>>> ''.join(map(str,seq))
'123456789'
>>> from random import randint
>>> lst = [randint(1,10) for i in range(50)] # 随机数列表
>>> lst
[8, 1, 10, 8, 7, 8, 7, 1, 1, 2, 4, 6, 1, 7, 10, 10, 9, 9, 6, 4, 8, 3, 5, 10, 10, 8, 3, 4, 9, 9, 1, 3, 6, 5, 1, 8, 5, 10, 10, 4, 5, 8, 10, 9, 8, 6, 7, 3, 10, 9]
>>> def tjNum(dic,k): # 统计元素出现次数
... if k in dic:... dic[k] += 1... else:... dic[k] = 1... return dic...>>> reduce(tjNum,lst,{}){8: 8, 1: 6, 10: 9, 7: 4, 2: 1, 4: 4, 6: 4, 9: 6, 3: 4, 5: 4} -
内置函数filter()将一个单参数作用到一个序列上,返回该序列中使用该函数返回值True的那些元素组成filter对象,如果指定函数为None,则返回序列中等价于Ture的元素
>>> seq = ['foo','x41','?! ','* * *']
>>> def func(x):
... return x.isalnum() # 测试是否为字母或数字
...
>>> filter(func,seq) # 返回filter对象
<filter object at 0x0000011DDB6F97F0>
>>> list(filter(func,seq))
['foo', 'x41']
>>> [x for x in seq if x.isalnum()] # 使用列表推导式实现相同功能
['foo', 'x41']
>>> list(filter(lambda x:x.isalnum(),seq)) # 使用lambda表达式实现相同功能
['foo', 'x41']
>>> list(filter(None,[1,2,3,0,0,4,0,5])) # 指定函数为None
[1, 2, 3, 4, 5]