[英]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.