簡體   English   中英

如何計算python中字典列表中的元素?

[英]how to count element inside lists of a dictionary in python?

假設我有一本這樣的字典:

allName = {
          'name1': ['sainz', 'gasly'], 
          'name2': ['sainz', 'gasly', 'stroll'],
          'name3': ['sainz', 'gasly', 'stroll']
}

我怎么知道sainz中有 3 個sainz名字、3 個 'gasly' 的名字、2 個 'stroll' 的名字?

我想像這樣打印出來:

sainz: 3
gasly: 3
stroll: 2

先謝謝了!

最簡單的方法可能是 collections counter 加上 itertools.chain

import itertools    
import collections
print(collections.Counter(itertools.chain(*data.values()))  

我認為會工作

使用collections.defaultdict

前任:

from collections import defaultdict

allName = {
          'name1': ['sainz', 'gasly'], 
          'name2': ['sainz', 'gasly', 'stroll'],
          'name3': ['sainz', 'gasly', 'stroll']
}

res = defaultdict(int)
for k, v in allName.items():
    for i in v:
        res[i]+=1
        
for k, v in res.items():
    print(f"{k}: {v}")     

輸出:

sainz: 3
gasly: 3
stroll: 2

另一種簡單的方法是從集合中使用 Counter

>>> from collections import Counter
>>> c = Counter()
>>> for names in allName.values():
...     for name in names:
...             c[name] += 1
...
>>> c
Counter({'sainz': 3, 'gasly': 3, 'stroll': 2})
>>>

解釋
loops :遍歷字典並找到列表中的所有項目。
count :然后將它們添加到計數器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM