簡體   English   中英

嵌套字典中值的百分比

[英]Percentage of values in a nested dictionary

我想獲得形式嵌套字典中值的百分比:

{'first': OrderedDict([('Jan', 2), ('Feb', 1)]), 'second': OrderedDict([('Jan', 3), ('Feb', 5)])}

預期的結果應該是這樣的:

{'first': OrderedDict([('Jan', 40%), ('Feb', 16.6%)]), 'second': OrderedDict([('Jan', 60%), ('Feb', 83.3%)])}

上述結果應以百分比形式獲得:對於鍵為“first”的字典:

Jan : 2/5 *100 = 40%
Feb: 1/6 *100 = 16.6%

對於鍵為“秒”的字典:

Jan : 3/5 *100 = 60%
Feb: 5/6 *100 = 83.3%

python 中的有序字典遵循一些特征作為普通字典,您可以使用.update('k': 'v') 更新值

for k, v in d.items(): v.update({'Jan': (v['Jan']/5)*100}) v.update({'Feb': (v['Feb']/6)*100})

上面的答案非常好,但如果你想獲得所有月份的總值,你可以嘗試兩次循環,首先對所有值求和,然后更新更改,例如:

x={'first': OrderedDict([('Jan', 2), ('Feb', 1)]), 'second': OrderedDict([('Jan', 3), ('Feb', 5)])}

total = [0]*2
for k in x :
    for idx, month in enumerate(x[k]):
        total[idx] += x[k][month]

for k, v in x.items():
    for idx, month in enumerate(v) : 
        v.update({month:round((v[month]/total[idx])*100,2)})

print(x)

這將生成 output 為:

{'first': OrderedDict([('Jan', 40.0), ('Feb', 16.67)]),
 'second': OrderedDict([('Jan', 60.0), ('Feb', 83.33)])}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM