Python代碼實(shí)現(xiàn)列表分組計(jì)數(shù)
本篇閱讀的代碼片段來自于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處理。