将字典的返回值表示为百分比(在Python中)

huangapple go评论75阅读模式
英文:

Return values of a dictionary as percentages (in Python)

问题

我有一个字典,列出了某事物出现的次数,但我想将这些次数转换为百分比。

假设字典如下:

s_dict = {'s1': 3,
          's2': 5,
          's3': 2}

我的初始方法类似于这样:

def rates_of_values(dictionary):
    d = {}
    for k, v in dictionary:
        d[k] = (dictionary[v] * 1.0 / sum(dictionary.values())) * 100

但这并不起作用,所以我简化了:

for k, v in heads:
     heads[k] = ((v / (sum(heads.values()))) * 100)

当我尝试以上的方法时,我收到了一个错误信息 'too many values to unpack (expected 2)'。
我成功地通过以下方式迭代字典并将值返回为百分比:

for value in heads.values():
     print(((value / (sum(heads.values()))) * 100))

但我想将它分配给一个新的字典,具有与原始键相同的键('s1','s2'...)。

提前谢谢!

英文:

I have a dictionary which lists the number of occurrences of something, but I want to turn those occurrences into percentages.

Suppose the dictionary is like this:

s_dict={'s1':3,
       's2':5,
       's3':2}

My initial approach was something like this:

def rates_of_values(dictionary):
    d={}
    for k, v in dictionary:
      d[k] = (dictionary[v] * 1.0 / sum(dictionary.values()))*100

But that didn't work, so I simplified:

for k, v in heads:
     heads[k] = ((v/(sum(heads.values())))*100)

When I try those above, I get an error 'too many values to unpack (expected 2)'.
I was able to iterate through the dictionary and return the values as percentages successfully with this:

for value in heads.values():
     print(((value/(sum(heads.values())))*100))

But I want to assign it to a new dictionary with the same original keys ('s1','s2'...)

Thank you in advance!!!

答案1

得分: -1

以下是要翻译的内容:

这是你正在寻找的答案。希望对你有帮助!

# 给定表示某些项出现次数的字典,此函数计算并返回每个项的百分比。

def calculate_percentages(dictionary):
    total_occurrences = sum(dictionary.values())
    percentages = {}

    for item, occurrences in dictionary.items():
        percentage = (occurrences / total_occurrences) * 100
        percentages[item] = percentage

    return percentages

# 示例用法:
s_dict = {'s1': 3, 's2': 5, 's3': 2}
result_dict = calculate_percentages(s_dict)
print(result_dict)

解释:

  1. calculate_percentages() 函数接受一个表示某些项出现次数的字典作为输入。
  2. 变量 total_occurrences 用于存储字典中所有值的总和。
  3. 创建一个名为 percentages 的新字典,用于存储每个项的计算百分比。
  4. 函数通过使用 .items() 遍历输入字典的键值对,其中 item 代表键,occurrences 代表值。
  5. 对于每个项,通过将其出现次数除以总出现次数,然后乘以 100 来计算相应的百分比。
  6. 将计算得到的百分比分配给 percentages 字典,以项作为键。
  7. 最后,函数返回 percentages 字典。
  8. 在示例用法中,将 s_dict 字典传递给 calculate_percentages() 函数,并将计算得到的百分比存储在 result_dict 字典中,然后将其打印出来。

此代码应正确计算字典中每个项的出现百分比。

英文:

Here is the answer you are looking for. Hope it helps!

# Given a dictionary representing the number of occurrences of certain items,
# this function calculates and returns the percentages for each item.

def calculate_percentages(dictionary):
    total_occurrences = sum(dictionary.values())
    percentages = {}

    for item, occurrences in dictionary.items():
        percentage = (occurrences / total_occurrences) * 100
        percentages[item] = percentage

    return percentages

# Example usage:
s_dict = {'s1': 3, 's2': 5, 's3': 2}
result_dict = calculate_percentages(s_dict)
print(result_dict)

Explanation:

  1. The calculate_percentages() function takes a dictionary as input representing the number of occurrences of certain items.
  2. The variable total_occurrences is used to store the sum of all the values in the dictionary.
  3. A new dictionary called percentages is created to store the calculated percentages for each item.
  4. The function iterates over the key-value pairs of the input dictionary using .items(), with item representing the key and occurrences representing the value.
  5. For each item, the corresponding percentage is calculated by dividing its occurrences by the total occurrences and then multiplying by 100.
  6. The calculated percentage is assigned to the percentages dictionary with the item as the key.
  7. Finally, the percentages dictionary is returned by the function.
  8. In the example usage, the s_dict dictionary is passed to the calculate_percentages() function, and the resulting percentages are stored in the result_dict dictionary, which is then printed.

This code should correctly calculate the percentages of occurrences for each item in the dictionary.

huangapple
  • 本文由 发表于 2023年7月3日 07:31:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定