简体   繁体   English

如何从Python中的列表计算项目?

[英]How do I compute items from a list in Python?

New here and in the process of learning Python. 在这里以及正在学习Python的过程中都是新的。

I am running through a scenario of taking office temperatures for the day. 我正在经历一种假设情况,即每天要考虑办公室温度。 Anything above 16 is placed into a second list where I would like to work out the percentages. 高于16的内容将放入第二个列表中,我想在其中列出百分比。 For example; 例如; 5 / 8 * 100 = 62% 5/8 * 100 = 62%

Here is what I currently have: 这是我目前拥有的:

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

Now my question is, and believe me I have Googled the life out of this the past couple days. 现在我的问题是,并相信我在过去的几天里,我已经度过了这一切。 How do I take the "output" list and do the percentage formula as above? 如何获取“输出”列表并执行上述百分比公式?

I have tried to create it in the for loop but to no avail. 我试图在for循环中创建它,但无济于事。

You can use len() to get the number of items in both lists and calculate a percentage from that. 您可以使用len()获取两个列表中的项目数,并从中计算百分比。

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

Use the list comprehension to build your list with elements: 使用列表推导来构建包含以下元素的列表:

list_temp = [16, 32, 5, 40, 10, 19, 38, 15]

lower = [i for i in list_temp if i >= 16] #your second list

percentage = len(lower)/len(list_temp) * 100
percentage
>>62.5

Then just get the percentage from the lengths. 然后只需从长度中获取百分比即可。

To create the list with only temps greater than 16, the easiest way is to use a list comprehension: 要创建仅具有大于16的温度的列表,最简单的方法是使用列表理解:

output = [temp for temp in list_temp if temp >= 16]

The above is equivalent to: 以上等同于:

output = []
for temp in list_temp:
    if temp >= 16:
        output.append(temp)

Then, to get the ratio: 然后,获取比率:

percentage = len(output) / len(list_temp) * 100
print(percentage) # 62.5

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

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