首页 > 解决方案 > 如何从 Python 中的列表中计算项目?

问题描述

新来的和学习 Python 的过程中。

我正在经历一个为一天测量办公室温度的场景。任何高于 16 的内容都被放入第二个列表中,我想在其中计算百分比。例如; 5 / 8 * 100 = 62%

这是我目前拥有的:

# List of temperatures taken from the office
list_temp = [16, 32, 5, 40, 10, 19, 38, 15]

# Output list above 16 degree celsius
output = []
total_output = 0

for position in list_temp:
    if position >= 16:
        output = output + [position]

print('Printing list of Temp Above 16', output)

现在我的问题是,相信我,在过去的几天里,我已经用谷歌搜索了这个生活。如何获取“输出”列表并执行上述百分比公式?

我试图在 for 循环中创建它,但无济于事。

标签: pythonpython-3.x

解决方案


您可以使用len()获取两个列表中的项目数并从中计算百分比。

>>>print('Percentage: ' + str(len(output)/len(list_temp)*100) + '%')
Percentage: 62.5%

推荐阅读