计算百分比列表以获得最终百分比。

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

Calculate list of percentage to get a final percentage

问题

我有些困难来计算一个百分比列表的最终百分比。

我的现有代码是:

bonus = [120, 11, 23, 92]

这个列表中的每个元素已经是一个百分比。

我想尝试编写一个函数来计算所有这些百分比,得到一个最终的百分比,如下所示:

120% + 11% + 23% + 92% = X%
英文:

I have some trouble to calcul a list of percentage to a final percentage

my actual code is

bonus = [120, 11, 23, 92]

everything in this list is already a percentage.

and I want a try to make a function that calcul all this percentage to have a final one, like

120% + 11% + 23% + 92% = X%

答案1

得分: 2

尝试使用sum()函数。

在你的情况下:

bonus = [120, 11, 23, 92]

final = sum(bonus)
英文:

Try the sum() function.

In your case:

bonus = [120, 11, 23, 92]

final = sum(bonus)

答案2

得分: 0

根据Pythoncraft的说法:尝试使用**sum()**函数。

然而,如果你希望在应用**sum()**函数之前将每个元素转换为百分比:

可以使用列表推导式。

语法:

new_list = [new_item for item in old_list]

在你的情况下:

new_list = [item/100 for item in bonus]

这等同于:

new_list = []
for item in bonus:
  percent = item/100
  new_list.append(percent)
英文:

As Pythoncraft stated above: Try the sum() function

However if you wish to convert each element into a percent before applying the sum() function:

Use List Comprehension.

syntax:

new_list = [new_item for item in old_list]

In your case:

new_list = [item/100 for item in bonus]

This is equivalent to:

new_list = []
for item in bonus:
  percent = item/100
  new_list.apend(percent)

答案3

得分: 0

你可以通过以下代码获取最终的百分比:

bonus = [120, 11, 23, 92]

listSum = str(sum(bonus)) + "%"
英文:

you can get the final percentage by the following code :

bonus = [120, 11, 23, 92]

listSum = str(sum(bonus))+"%"

huangapple
  • 本文由 发表于 2023年8月9日 01:56:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862089.html
匿名

发表评论

匿名网友

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

确定