I have an array and I want to count the occurrence of each item in the array.
I have managed to use a map function to produce a list of tuples.
def
If all you need is cnt
, then a dict
would probably be better than a list
of tuple
s here (if you need this format, just use dict.items
).
The collections
module has a useful data structure for this, a defaultdict
.
from collections import defaultdict
cnt = defaultdict(int) # create a default dict where the default value is
# the result of calling int
for key in arr:
cnt[key] += 1 # if key is not in cnt, it will put in the default
# cnt_list = list(cnt.items())