人妖在线一区,国产日韩欧美一区二区综合在线,国产啪精品视频网站免费,欧美内射深插日本少妇

新聞動(dòng)態(tài)

Python代碼實(shí)現(xiàn)列表分組計(jì)數(shù)

發(fā)布日期:2021-12-12 05:49 | 文章來源:源碼之家

本篇閱讀的代碼片段來自于30-seconds-of-python。

1. count_by

def count_by(arr, fn=lambda x: x):
  key = {}
  for el in map(fn, arr):
 key[el] = 1 if el not in key else key[el] + 1
  return key
# EXAMPLES
from math import floor
count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1}
count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1}

count_by根據(jù)給定的函數(shù)對(duì)列表中的元素進(jìn)行分組,并返回每組中元素的數(shù)量。該使用map()使用給定函數(shù)映射給定列表的值。在映射上迭代,并在每次出現(xiàn)時(shí)增加元素?cái)?shù)。

該函數(shù)使用not in判斷目前字典中是否含有指定的key,如果不含有,就將該key加入字典,并將對(duì)應(yīng)的value設(shè)置為1;如果含有,就將value加1。

2. 使用字典推導(dǎo)式

字典推導(dǎo)式有{ key_expr: value_expr for value in collection if condition }這樣的形式。group_by函數(shù)中字典推導(dǎo)式的value_expr是一個(gè)列表,該列表使用了列表推導(dǎo)式來生成。即

{ key_expr: [x for x in collection2 if condition2] for value in collection1 if condition1 }

同時(shí),我們可以看到根據(jù)group_by代碼中的字典推導(dǎo)式,可能計(jì)算出key相同的項(xiàng),根據(jù)Pyrhon中字典的類型的規(guī)則,key相同的,只保留最新的key-value對(duì)。實(shí)際上當(dāng)key相同時(shí),value值也一樣。[el for el in lst if fn(el) == key]推導(dǎo)式的for語(yǔ)句中只有key一個(gè)變量。

>>> d = {'one': 1, 'two': 2, 'three': 3, 'two': 2}
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> d = {'one': 1, 'two': 2, 'three': 3, 'two': 22}
>>> d
{'one': 1, 'two': 22, 'three': 3}
>>>

這里也可以使用同樣的方式,在分組之后直接獲取列表長(zhǎng)度。不過這種寫法遍歷了兩次列表,會(huì)使程序效率變低。

def count_by(lst, fn):
  return {key : len([el for el in lst if fn(el) == key]) for key in map(fn, lst)}

3. 使用collections.defaultdict簡(jiǎn)化代碼

class collections.defaultdict([default_factory[, ...]])

collections.defaultdict包含一個(gè)default_factory屬性,可以用來快速構(gòu)造指定樣式的字典。

當(dāng)使用int作為default_factory,可以使defaultdict用于計(jì)數(shù)。因此可以直接使用它來簡(jiǎn)化代碼。相比字典推導(dǎo)式的方法,只需要對(duì)列表進(jìn)行一次循環(huán)即可。

 from collections import defaultdict
def count_by(lst, fn):
  d = defaultdict(int)
  for el in lst:
 d[fn(el)] += 1
  return d

當(dāng)使用 list 作為 default_factory時(shí),很輕松地將(鍵-值對(duì)組成的)序列轉(zhuǎn)換為(鍵-列表組成的)字典。

def group_by(lst, fn):
  d = defaultdict(list)
  for el in lst:
 d[fn(el)].append(el)
  return d
# EXAMPLES
from math import floor
group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]}
group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']}

到此這篇關(guān)于Python代碼實(shí)現(xiàn)列表分組計(jì)數(shù)的文章就介紹到這了,更多相關(guān)Python列表分組計(jì)數(shù)內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!

版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。

相關(guān)文章

實(shí)時(shí)開通

自選配置、實(shí)時(shí)開通

免備案

全球線路精選!

全天候客戶服務(wù)

7x24全年不間斷在線

專屬顧問服務(wù)

1對(duì)1客戶咨詢顧問

在線
客服

在線客服:7*24小時(shí)在線

客服
熱線

400-630-3752
7*24小時(shí)客服服務(wù)熱線

關(guān)注
微信

關(guān)注官方微信
頂部