[英]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:您需要使用元组而不是列表将它们用作字典键(键需要是可散列的),但如果这不是问题,您可以使用
collections.counter
来应对变化,然后是字典理解:
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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.