Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting frequencies in two lists, Python

I'm new to programming in python so please bear over with my newbie question...

I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2):

list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],

list2 = [13, 19, 2, 16, 6, 5, 20, 21]

What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong.

The output I am looking for is something similar to this:

Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1.

like image 912
AH7 Avatar asked Dec 08 '22 21:12

AH7


1 Answers

The easiest way is to use a counter:

from collections import Counter
list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16]
c = Counter(list1)
print(c)

giving

Counter({2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1})

So you can access the key-value-pairs of the counter representing the items and its occurrences using the same syntax used for acessing dicts:

for k, v in c.items():
    print('- Element {} has {} occurrences'.format(k, v))

giving:

- Element 16 has 2 occurrences
- Element 2 has 1 occurrences
- Element 19 has 3 occurrences
- Element 20 has 2 occurrences
- Element 5 has 1 occurrences
- Element 6 has 1 occurrences
- Element 13 has 4 occurrences
- Element 21 has 1 occurrences
like image 153
albert Avatar answered Dec 22 '22 00:12

albert