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

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

 更新時(shí)間:2021年11月11日 15:31:14   作者:Felix  
這篇文章主要介紹了Python代碼實(shí)現(xiàn)列表分組計(jì)數(shù),利用Python代碼實(shí)現(xiàn)了使用分組函數(shù)對列表進(jìn)行分組,并計(jì)算每組的元素個(gè)數(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ù)對列表中的元素進(jìn)行分組,并返回每組中元素的數(shù)量。該使用map()使用給定函數(shù)映射給定列表的值。在映射上迭代,并在每次出現(xiàn)時(shí)增加元素?cái)?shù)。

該函數(shù)使用not in判斷目前字典中是否含有指定的key,如果不含有,就將該key加入字典,并將對應(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對。實(shí)際上當(dāng)key相同時(shí),value值也一樣。[el for el in lst if fn(el) == key]推導(dǎo)式的for語句中只有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}
>>>

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

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簡化代碼

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


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

當(dāng)使用int作為default_factory,可以使defaultdict用于計(jì)數(shù)。因此可以直接使用它來簡化代碼。相比字典推導(dǎo)式的方法,只需要對列表進(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í),很輕松地將(鍵-值對組成的)序列轉(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論