Reputation: 21
I have a list of lists that I would like to transform into a dictionary of relative frequencies.
List of lists:
[['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d', 'SBS38'],
['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']]
Dictionary of relative frequencies of the list of lists
{['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']: 0.6,
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']: 0.2,
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d', 'SBS38']: 0.2}
How can I do this?
Upvotes: 0
Views: 95
Reputation: 92440
You'll need to use tuples rather than lists use them as dict keys (keys need to be hashable), but if that's not a problem, you can use collections.counter
to counter the variations, then a dict comprehension:
from collections import Counter
l = [['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'],
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d', 'SBS38'],
['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']]
counts = Counter(map(tuple,l))
result = {k:count/len(l) for k, count in counts.items()}
result:
{('SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'): 0.6,
('SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d'): 0.2,
('SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d', 'SBS38'): 0.2}
Upvotes: 2