Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the frequency of the elements in an unordered list?

People also ask

How do you count the number of repeated elements in a list?

from collections import Counter MyList = ["a", "b", "a", "c", "c", "a", "c"] duplicate_dict = Counter(MyList) print(duplicate_dict)#to get occurence of each of the element. print(duplicate_dict['a'])# to get occurence of specific element. remember to import the Counter if you are using Method otherwise you get error.


In Python 2.7 (or newer), you can use collections.Counter:

import collections

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)

print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})

print(counter.values())
# [4, 4, 2, 1, 2]

print(counter.keys())
# [1, 2, 3, 4, 5]

print(counter.most_common(3))
# [(1, 4), (2, 4), (3, 2)]

print(dict(counter))
# {1: 4, 2: 4, 3: 2, 5: 2, 4: 1}

If you are using Python 2.6 or older, you can download it here.


Note: You should sort the list before using groupby.

You can use groupby from itertools package if the list is an ordered list.

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]

Output:

[4, 4, 2, 1, 2]

update: Note that sorting takes O(n log(n)) time.


Python 2.7+ introduces Dictionary Comprehension. Building the dictionary from the list will get you the count as well as get rid of duplicates.

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]

To count the number of appearances:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1

To remove duplicates:

a = set(a) 

In Python 2.7+, you could use collections.Counter to count items

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]