简体   繁体   English

计算字典值的百分比

[英]Calculate percentage of dictionary values

all_brands_scores  = dict(sorted(all_brands_scores.items(), key=lambda item: item[1]))
print(all_brands_scores )

output:输出:

{'ADATA': 0, 'GIGABYTE': 0, 'CyberPowerPC': 0, 'Hyundai': 0, 'Thomson': 0, 'KANO': 1, 'Alienware': 1, 'Razer': 1, 'Google': 1, 'LG': 2, 'HP OMEN': 5, 'Acer': 12, 'Apple': 13, 'Microsoft': 13, 'MSI': 17, 'Samsung': 18, 'Dell': 24, 'ASUS': 54, 'Lenovo': 71, 'HP': 104} {'ADATA':0,'GIGABYTE':0,'Cyber​​PowerPC':0,'Hyundai':0,'Thomson':0,'KANO':1,'Alienware':1,'Razer':1,' Google':1,'LG':2,'HP OMEN':5,'Acer':12,'Apple':13,'Microsoft':13,'MSI':17,'Samsung':18,'Dell ':24,'华硕':54,'联想':71,'HP':104}

I have this file(dic) but not as fixed values How do I calculate the percentage of each type of laptop ?我有这个文件(dic)但不是固定值 如何计算每种笔记本电脑的百分比?

If you want to replace the original values with their percentages:如果您想用百分比替换原始值:

total = sum(all_brands_scores.values())
for key,val in all_brands_scores.items():
    all_brands_scores[key] = round(val/total * 100, 2)

If you want a new dictionary of percentages:如果你想要一本新的百分比字典:

perc_dict = {}
total = sum(all_brands_scores.values())
    for key,val in all_brands_scores.items():
        perc_dict[key] = round(val/total * 100, 2)

If you want to add the % symbol, then you will have to convert the values into string format:如果要添加 % 符号,则必须将值转换为字符串格式:

perc_dict = {}
total = sum(all_brands_scores.values())
for key,val in all_brands_scores.items():
    perc_dict[key] = str(round(val/total * 100, 2)) + '%'

(Rounding off the percentages till 2 decimal places.) (将百分比四舍五入到小数点后 2 位。)

sum_of_values = sum(data.values())
dict(
    map(
        lambda v: 
            [
                v[0],
                str(v[1] / sum_of_values * 100) + "%"
            ],
            data.items()
        )
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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