计算字典值的百分比

发布于 2025-02-10 04:14:07 字数 399 浏览 2 评论 0原文

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

输出:

态 '汤姆森':0,'kano':1,'alienware':1,'razer':1,'google':1, 'lg':2,'hp omen':5,'acer':12,'苹果:13,'Microsoft':13, 'MSI':17,'Samsung':18,'Dell':24,“ Asus”:54,'Lenovo':71,'HP': 104}

我有这个文件(DIC),但不为固定值 如何计算每种笔记本电脑的百分比?

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}

I have this file(dic) but not as fixed values
How do I calculate the percentage of each type of laptop ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等你爱我 2025-02-17 04:14:07

如果要用其百分比替换原始值:

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

如果您需要一个新的百分比字典:

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

如果要添加%符号,则必须将值转换为字符串格式

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)) + '%'

:地方。)

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.)

年少掌心 2025-02-17 04:14:07
sum_of_values = sum(data.values())
dict(
    map(
        lambda v: 
            [
                v[0],
                str(v[1] / sum_of_values * 100) + "%"
            ],
            data.items()
        )
    )
sum_of_values = sum(data.values())
dict(
    map(
        lambda v: 
            [
                v[0],
                str(v[1] / sum_of_values * 100) + "%"
            ],
            data.items()
        )
    )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文