I have two lists like the following:
JavaScript
x
3
1
l1= ['a','b','c','a','b','c','c','c']
2
l2= ['f','g','f','f','f','g','f','f']
3
I have tried to get the counts of elements in the first list based on a condition:
JavaScript
1
3
1
from collections import Counter
2
Counter([a for a, b in zip(l1, l2) if b == 'f'])
3
the output is:
JavaScript
1
2
1
Counter({'a': 2, 'c': 3, 'b': 1})
2
instead of counts, I would like to get their percentage like the following
JavaScript
1
2
1
'a': 1, 'c': 0.5, 'b': 0.75
2
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:
JavaScript
1
10
10
1
from collections import Counter
2
3
l1= ['a','b','c','a','b','c','c','c']
4
l2= ['f','g','f','f','f','g','f','f']
5
6
d=dict(Counter([a for a,b in zip(l1,l2) if b=='f']))
7
8
k={i:j/100 for i,j in d.items()}
9
print(k)
10
To calculate percentage:
JavaScript
1
3
1
k={i:(j/l1.count(i)) for i,j in d.items()}
2
print(k)
3