gpt4 book ai didi

python - 如何计算列表中满足特定条件的元素的百分比?

转载 作者:行者123 更新时间:2023-11-28 08:11:03 24 4
gpt4 key购买 nike

我正在制作一个程序来查看包含美国冰雹数据的文件。我已经成功创建了一个包含对象(所有州)的类,并且包含州缩写、冰雹报告总数和冰雹列表每个状态/对象的大小。

我必须制作一个表格来显示每个州冰雹大小的统计数据。我创建了一种方法来计算每个州的冰雹大小的平均值,但我不知道如何制作一种方法来计算落在特定大小范围内的冰雹大小的百分比。

该表有 5 个类别,对于这些冰雹大小:<1.25、1.25-1.99、2.0-2.49、2.5-2.99、>3.0。
我很确定我需要为每个类别做一个滚动总和,但我不知道如何对这么多类别进行计算。如果我可以做一个滚动总和,它就是那个总和/该州的报告总数。

这是我目前的代码:

class stateHail:
def __init__(self, state):
self.stateAbbr = state
self.hailReports = 0
self.hailSize = []

def avgSize(self):
self.avg = (sum(self.hailSize))/self.hailReports

#def percents(self):
#???

#Creates objects needed for class

states = []
for x in ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "WA", "WV", "WI", "WY", "PR", "VA", "VI"]:
stateObject = stateHail(x)
states.append(stateObject)

#Opens file and assigns state abbreviation, hail report number, and list of hail sizes to each object/state

fileHail = open("90-99_hail.csv", "r")
try:
for line in fileHail:
splitLine=line.split(",")
abbrFile=splitLine[7]
for x in states:
if (abbrFile==x.stateAbbr):
x.hailSize.append(float(splitLine[10]))
x.hailReports = x.hailReports + 1

except:
fileHail.close()

#Calculates average for each state

for x in states:
if (x.hailReports>100):
x.avgSize()
print x.avg

最佳答案

如果我正确理解你的问题,那么你可以将每个范围的百分比存储在一个列表中。代码可能如下所示

    self.percentages = [(self.hailSize[i]/self.hailReports) * 100 for i in range(5)]

关于python - 如何计算列表中满足特定条件的元素的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com