當前位置:成語大全網 - 新華字典 - 深入理解Python reduce函數

深入理解Python reduce函數

例如上面的例子,實現壹個整形集合的累加。假設lst = [1,2,3,4,5],實現累加的方式有很多:

第壹種:用sum函數。

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

return add(lst,temp)

else:

return result

if name ==" main ":

lst = [1,2,3,4,5]

print add(lst,0)

第四種:reduce方式

lst = [1,2,3,4,5]

print reduce(lambda x,y:x+y,lst)

lst = [1,2,3,4,5]

print reduce(lambda x,y:x+y,lst,0)

def add(x,y):

return x+y

print reduce(add, lst)

def add(x,y):

return x+y

print reduce(add, lst,0)

有壹個序列集合,例如[1,1,2,3,2,3,3,5,6,7,7,6,5,5,5],統計這個集合所有鍵的重復個數,例如1出現了兩次,2出現了兩次等。大致的思路就是用字典存儲,元素就是字典的key,出現的次數就是字典的value。方法依然很多

第壹種:for循環判斷

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

第二種:比較取巧的,先把列表用set方式去重,然後用列表的count方法

def statistics2(lst):

m = set(lst)

dic = {}

for x in m:

dic[x] = lst.count(x)

lst = [1,1,2,3,2,3,3,5,6,7,7,6,5,5,5]

print statistics2(lst)

第三種:用reduce方式

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,{})

或者

d = {}

d.extend(lst)

print reduce(statistics,d)

通過上面的例子發現,凡是要對壹個集合進行操作的,並且要有壹個統計結果的,能夠用循環或者遞歸方式解決的問題,壹般情況下都可以用reduce方式實現。