zara kolagar
zara kolagar

Reputation: 901

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.

Upvotes: 2

Views: 1730

Answers (3)

Ram
Ram

Reputation: 4779

Calculate the frequency of characters in l1 and perform division to get percentage.

In your code b percentage should be 0.5 and not 0.75

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

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

c = {i:(v/a[i]) for i,v in c.items()}
print(c)
{'a': 1.0, 'c': 0.75, 'b': 0.50}

Upvotes: 1

user15801675
user15801675

Reputation:

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)

Upvotes: 1

mpenalozag
mpenalozag

Reputation: 89

Do you specifically need it to be done in one line ? If not, maybe this could work:

from collections import Counter
l1= ['a','b','c','a','b','c','c','c']
l2= ['f','g','f','f','f','g','f','f']


alpha = Counter([a for a,b in zip(l1,l2) if b=='f'])
for key, item in alpha.items():
    alpha[key] = int(item)/100

print(alpha)

Upvotes: 1

Related Questions