# 跟老齐学python之大话题小函数(2)

reduce

>>> reduce(lambda x,y: x+y,[1,2,3,4,5])
15

>>> list1 = [1,2,3,4,5,6,7,8,9]
>>> list2 = [9,8,7,6,5,4,3,2,1]
>>> map(lambda x,y: x+y, list1,list2)
[10, 10, 10, 10, 10, 10, 10, 10, 10]

reduce(function, iterable[, initializer])

apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. for example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). the left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. if the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. if initializer is not given and iterable contains only one item, the first item is returned. roughly equivalent to:

def reduce(function, iterable, initializer=none):
it = iter(iterable)
if initializer is none:
try:
initializer = next(it)
except stopiteration:
raise typeerror(‘reduce() of empty sequence with no initial value’)
accum_value = initializer
for x in it:
accum_value = function(accum_value, x)
return accum_value

>>> lst = range(1,6)
>>> lst
[1, 2, 3, 4, 5]
>>> r = 0
>>> for i in range(len(lst)):
… r += lst[i]

>>> r
15

for普世的，reduce是简洁的。

>>> a
[3, 9, 8, 5, 2]
>>> b
[1, 4, 9, 2, 6]

>>> zip(a,b) #复习一下zip，下面的方法中要用到
[(3, 1), (9, 4), (8, 9), (5, 2), (2, 6)]

>>> sum(x*y for x,y in zip(a,b)) #解析后直接求和
133

>>> new_list = [x*y for x,y in zip(a,b)] #可以看做是上面方法的分布实施
>>> #这样解析也可以：new_tuple = (x*y for x,y in zip(a,b))
>>> new_list
[3, 36, 72, 10, 12]
>>> sum(new_list) #或者:sum(new_tuple)
133

>>> reduce(lambda sum,(x,y): sum+x*y,zip(a,b),0) #这个方法是在耍酷呢吗？
133

>>> from operator import add,mul #耍酷的方法也不止一个
133

>>> reduce(lambda x,y: x+y, map(lambda x,y: x*y, a,b)) #map,reduce,lambda都齐全了，更酷吗？
133

filter

filter的中文含义是“过滤器”，在python中，它就是起到了过滤器的作用。首先看官方说明：

filter(function, iterable)

construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. if iterable is a string or a tuple, the result also has that type; otherwise it is always a list. if function is none, the identity function is assumed, that is, all elements of iterable that are false are removed.

note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not none and [item for item in iterable if item] if function is none.

>>> numbers = range(-5,5)
>>> numbers
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>> filter(lambda x: x>0, numbers)
[1, 2, 3, 4]

>>> [x for x in numbers if x>0] #与上面那句等效
[1, 2, 3, 4]

>>> filter(lambda c: c!=’i’, ‘qiwsir’) #能不能对应上面文档说明那句话呢？
‘qwsr’ #“if iterable is a string or a tuple, the result also has that type;”

Posted in 未分类