本篇閱讀的代碼實現了使用分組函數對列表進行分組,並計算每組的元素個數的功能。
本篇閱讀的代碼片段來自於30-seconds-of-python。
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根據給定的函數對列表中的元素進行分組,並返回每組中元素的數量。該使用map()使用給定函數映射給定列表的值。在映射上迭代,並在每次出現時增加元素數。
該函數使用not in判斷目前字典中是否含有指定的key,如果不含有,就將該key加入字典,並將對應的value設置為1;如果含有,就將value加1。
使用字典推導式
在** Python代碼閱讀:根據給定的函數對列表中的元素進行分組**中使用了字典推導式,將列表進行了分組。這里也可以使用同樣的方式,在分組之后直接獲取列表長度。不過這種寫法遍歷了兩次列表,會使程序效率變低。
def count_by(lst, fn):
return {key : len([el for el in lst if fn(el) == key]) for key in map(fn, lst)}
使用collections.defaultdict簡化代碼
class collections.defaultdict([default_factory[, ...]])
collections.defaultdict包含一個default_factory屬性,可以用來快速構造指定樣式的字典。
當使用int作為default_factory,可以使defaultdict用於計數。因此可以直接使用它來簡化代碼。相比字典推導式的方法,只需要對列表進行一次循環即可。
from collections import defaultdict
def count_by(lst, fn):
d = defaultdict(int)
for el in lst:
d[fn(el)] += 1
return d
當使用 list 作為 default_factory時,很輕松地將(鍵-值對組成的)序列轉換為(鍵-列表組成的)字典。因此我們也可以據此改寫** Python代碼閱讀:根據給定的函數對列表中的元素進行分組**中的實現方式,提高效率。
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']}
