[英]How to convert a list of lists into a dictionary of relative frequencies?
我有一个列表列表,我想将其转换为相对频率字典。
列表列表:
[['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']]
列表列表的相对频率字典
{['SBS1', 'SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']: 0.6,
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d']: 0.2,
['SBS5', 'SBS7a', 'SBS7b', 'SBS7c', 'SBS7d', 'SBS38']: 0.2}
我怎样才能做到这一点?
您需要使用元组而不是列表将它们用作字典键(键需要是可散列的),但如果这不是问题,您可以使用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()}
结果:
{('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.