简体   繁体   中英

How to convert a list of lists into a dictionary of relative frequencies?

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?

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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM