简体   繁体   中英

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

I have a defined list as list =["a","b","d","f","g","a","g","d","a","d"] and I want a dictionary like this dicc = {a:2, b:1, d:3, f:1, g:2} . The values in this dictionary are the number of times that the element of the list is repeated in the list. I tried the folowing but I dont know what to put in the # .

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}

This is exactly what the Counter class does.

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

Counter is a subclass of dict so you can use it as a dict.

You dont have to use len(list) in case as python is very flexible and you have count() for lists.

Solution:

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}

Or you can use Counter as mentioned in the comment. I will include the link where a similar example is given. In case you just have to call

dicc = dict(Counter(list))

This is because:

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

Still if you want the code as you have given you can use the below code. But its not the best way.

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

Both the solutions are same, first one shows the beauty of python. Hope you got your answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM