如何计算列表中符合特定条件的项目百分比?

时间:2015-03-25 19:51:56

标签: python css object methods

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

我必须制作一张表格,显示每个州的冰雹大小统计数据。我创建了一种平均每种状态冰雹大小的方法,但我无法弄清楚如何制作一种方法来计算落在一定大小范围内的冰雹大小的百分比。

对于这些冰雹尺寸,该表有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




2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

如果您有像这样的冰雹大小列表:[1.1,1.1,1.6,1.6,2.1,2.6,3.1,3.1,3.1]

您可以获得如下列表:[2, 2, 1, 1, 3]

来自:

return [len([item for item in self.hailSize if small<=item<big]) for small,big in [(0,1.25), (1.25,2), (2,2.5), (2.5,3), (3,200)]]

顺便说一下,您可以只使用self.hailReports,而不是保存self.hailSize变量来计算len(self.hailSize)中有多少元素。接下来,让avgSize()只执行return sum(self.hailSize)/len(self.hailSize),然后您不必一直调用函数来更新变量 - 只需使用avgSize()获取平均大小。