# Python----reduce原来是这样用的

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 iterable:
accum_value = function(accum_value, x)
return accum_value```

`sum(lst)`

```def customer_sum(lst):
result = 0
for x in lst:
result+=x
return result

#或者
def customer_sum(lst):
result = 0
while lst:
temp = lst.pop(0)
result+=temp
return result

if __name__=="__main__":
lst = [1,2,3,4,5]
print customer_sum(lst)```

```def add(lst,result):
if lst:
temp = lst.pop(0)
temp+=result
else:
return result

if __name__=="__main__":
lst = [1,2,3,4,5]

```lst = [1,2,3,4,5]
print reduce(lambda x,y:x+y,lst)
#这种方式用lambda表示当做参数，因为没有提供reduce的第三个参数，所以第一次执行时x=1,y=2,第二次x=1+2,y=3,即列表的第三个元素

#或者
lst = [1,2,3,4,5]
print reduce(lambda x,y:x+y,lst,0)
#这种方式用lambda表示当做参数，因为指定了reduce的第三个参数为0，所以第一次执行时x=0,y=1,第二次x=0+1,y=2,即列表的第二个元素，

#或者
return x+y

#与方式1相同，只不过把lambda表达式换成了自定义函数

#或者
return x+y

#与方式2相同，只不过把lambda表达式换成了自定义函数```

```def statistics(lst):
dic = {}
for k in lst:
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print(statistics(lst))```

```def statistics2(lst):
m = set(lst)
dic = {}
for x in m:
dic[x] = lst.count(x)

return dic

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print statistics2(lst)```

```def statistics(dic,k):
if not k in dic:
dic[k] = 1
else:
dic[k] +=1
return dic

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]
print reduce(statistics,lst,{})
#提供第三个参数，第一次，初始字典为空，作为statistics的第一个参数，然后遍历lst,作为第二个参数，然后将返回的字典集合作为下一次的第一个参数

d = {}
d.extend(lst)
print reduce(statistics,d)
#不提供第三个参数，但是要在保证集合的第一个元素是一个字典对象，作为statistics的第一个参数，遍历集合依次作为第二个参数```

reduce函数真是“一位好同志啊”！

65 篇文章34 人订阅

0 条评论

## 相关文章

36080

6720

26670

### 第202天：js---原型与原型链终极详解

JavaScript 中，万物皆对象！但对象也是有区别的。分为普通对象和函数对象，Object 、Function 是 JS 自带的函数对象。下面举例说明

19820

21250

18020

13140

35360

44340

25500