簡體   English   中英

計算列表字典中的頻率

[英]Counting frequencies in a dictionary of lists

我有一本帶有一堆列表的字典,即:

{"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], etc...}

如何計算每個列表中數字的頻率? 和 output 格式的字典:

{"0": {"0": 4, "1": 2}, "1": {"0": 12, "1": 4}, etc..}

使用collections.Counter

from collections import Counter

spam = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}
eggs = {key:Counter(value) for key, value in spam.items()}
print(eggs)

output:

{'0': Counter({0: 4, 1: 2}), '1': Counter({0: 12, 1: 4})}

當然,如果您願意,您可以將Counter轉換為dict

您始終可以自己制作一個計數器,它只計算列表中每個元素的出現次數(請注意,您可以使用 integer 作為字典鍵,而不僅僅是字符串)。 像這樣:

a = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}
different_a = dict()
for key in a.keys():
  counting_dict = dict()
  for e in a[key]:
    if str(e) in counting_dict:
      counting_dict[str(e)] += 1
    else:
      counting_dict[str(e)] = 1
  different_a[key] = counting_dict

但是讓我們看一個比僅僅計算元素數量更好的方法。

我最喜歡的是使用 collections.Counter:

from collections import Counter
new_a = {key: Counter(value) for key, value in a.items()}

它將列表變成一個集合(一種列表,其中每個元素只能出現一次,元素的順序沒有意義),並增加了計算出現次數的功能。 在此處閱讀有關此數據結構的更多信息。

試試這個(d是你的字典):

d={"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]}

res={i:{'0':k.count(0), '1':k.count(1)} for i,k in d.items()}

>>>print(res)

{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}

你可以這樣做

d = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],}

a = dict()

for k,v in d.items():
    count = dict()
    for x in set(v):
        count[str(x)] = v.count(x)
    a[k] = count
    
print(a)

Output:

{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}

或者您可以使用字典理解來做到這一點:

d = {"0": [0, 0, 0, 0, 1, 1], "1": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1],}

a = {k:{str(x):v.count(x) for x in set(v)} for k,v in d.items()}

print(a)

Output:

{'0': {'0': 4, '1': 2}, '1': {'0': 12, '1': 4}}

暫無
暫無

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

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