簡體   English   中英

如何生成每個元素到其出現次數的映射?

[英]How can I produce a mapping of each element to the number of times it occurs?

我有一個定義的列表,如list =["a","b","d","f","g","a","g","d","a","d"]和我想要像這樣的字典dicc = {a:2, b:1, d:3, f:1, g:2} 該詞典中的值是列表中的元素在列表中重復的次數。 我嘗試了以下操作,但是我不知道在#要放什么。

dicc = dict(zip(list,[# for x in range(#c.,len(list))]))


lista = ["a","b","d","f","g","a","g","d","a","d"]
dicc = dict(zip(list,[# for x in range(#c.,len(list))]))
print dicc 
dicc = {a:2, b:1, d:3, f:1, g:2}

這正是Counter類所做的。

from collections import Counter
Counter(lista)
=> Counter({'d': 3, 'a': 3, 'g': 2, 'b': 1, 'f': 1})

Counterdict的子類,因此您可以將其用作dict。

您不必使用len(list)以防python非常靈活並且列表具有count()。

解:

lista = ["a","b","d","f","g","a","g","d","a","d"]
dicc = dict(zip(list,[list.count(x) for x in list]))
print dicc 
>>>dicc = {a:2, b:1, d:3, f:1, g:2}

或者,您可以使用注釋中提到的Counter。 我將在給出類似示例的地方添加鏈接 萬一你只需要打電話

dicc = dict(Counter(list))

這是因為:

type(Counter(list)) -> collections.Counter

不過,如果您想要的是您提供的代碼,則可以使用以下代碼。 但這不是最好的方法。

dicc = dict(zip(list,[list.count(list[x]) for x in range(len(list))]))

兩種解決方案都是相同的,第一個顯示了python的美麗。 希望你能得到答案。

暫無
暫無

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

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