Skip to content
Advertisement

python: get percentage from collection counter

I have two lists like the following:

l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']

I have tried to get the counts of elements in the first list based on a condition:

from collections import Counter
Counter([a for a, b in zip(l1, l2) if b == 'f'])

the output is:

Counter({'a': 2, 'c': 3, 'b': 1})

instead of counts, I would like to get their percentage like the following

'a': 1, 'c': 0.5, 'b': 0.75

I have tried adding Counter(100/([a for a,b in zip(l1,l2) if b=='f'])), but I get an error.

Advertisement

Answer

You can try this:

from collections import Counter

l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']

d=dict(Counter([a for a,b in zip(l1,l2) if b=='f']))

k={i:j/100 for i,j in d.items()}
print(k)

To calculate percentage:

k={i:(j/l1.count(i)) for i,j in d.items()}
print(k)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement