欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python的化簡(jiǎn)函數(shù)reduce()詳解

 更新時(shí)間:2023年12月26日 08:46:45   作者:wrr-cat  
這篇文章主要介紹了Python的化簡(jiǎn)函數(shù)reduce()詳解,reduce()函數(shù)即為化簡(jiǎn)函數(shù),它的執(zhí)行過程為:每一次迭代,都將上一次的迭代結(jié)果與下一個(gè)元素一同傳入二元func函數(shù)中去執(zhí)行,需要的朋友可以參考下

一、前言

官方解釋如下:

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence 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 sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

格式:

creduce (func, seq[, init()])

reduce()函數(shù)即為化簡(jiǎn)函數(shù),它的執(zhí)行過程為:每一次迭代,都將上一次的迭代結(jié)果(注:第一次為init元素,如果沒有指定 init 則為 seq 的第一個(gè)元素)與下一個(gè)元素一同傳入二元func函數(shù)中去執(zhí)行。在reduce()函數(shù)中,init 是可選的,如果指定,則作為第一次迭代的第一個(gè)元素使用,如果沒有指定,就取 seq 中的第一個(gè)元素。

二、舉例

有一個(gè)序列集合,例如[1,1,2,3,2,3,3,5,6,7,7,6,5,5,5],統(tǒng)計(jì)這個(gè)集合所有鍵的重復(fù)個(gè)數(shù),例如 1 出現(xiàn)了兩次,2 出現(xiàn)了兩次等。

大致的思路就是用字典存儲(chǔ),元素就是字典的 key,出現(xiàn)的次數(shù)就是字典的 value。

方法依然很多第一種:for 循環(huán)判斷

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) 
  return dic
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,{}) 
#提供第三個(gè)參數(shù),第一次,初始字典為空,作為statistics的第一個(gè)參數(shù),然后遍歷lst,作為第二個(gè)參數(shù),然后將返回的字典集合作為下一次的第一個(gè)參數(shù)

或者

d = {} 
d.extend(lst) 
print reduce(statistics,d) 
#不提供第三個(gè)參數(shù),但是要在保證集合的第一個(gè)元素是一個(gè)字典對(duì)象,作為statistics的第一個(gè)參數(shù),遍歷集合依次作為第二個(gè)參數(shù) 

通過上面的例子發(fā)現(xiàn),凡是要對(duì)一個(gè)集合進(jìn)行操作的,并且要有一個(gè)統(tǒng)計(jì)結(jié)果的,能夠用循環(huán)或者遞歸方式解決的問題,一般情況下都可以用reduce方式實(shí)現(xiàn)。

到此這篇關(guān)于Python的化簡(jiǎn)函數(shù)reduce()詳解的文章就介紹到這了,更多相關(guān)Python的reduce()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論