Python:在列表中汇总类实例

时间:2011-08-03 01:19:15

标签: python class list sum instances

我熟悉列表的内置sum()函数,之前已经使用过它,例如:

sum(list1[0:41])

当列表包含整数时,但我遇到的情况是我有一个类的实例,我需要它们总结。

我有这个班级:

class DataPoint:
    def __init__(self, low, high, freq):
        self.low = low
        self.high = high
        self.freq = freq

它们都引用XML文件中的浮点数,这些实例稍后会进入我的代码中的列表。

例如,我希望能够做到这样的事情:

sum(list[0:41].freq)

其中列表包含Class实例。

我也试图在循环中得到它,以便sum()范围内的第二个数字每次都上升,例如:

for i in range(len(list)):
    sum(list[0:i+1].freq)

任何人都知道如何解决这个问题,或者有其他办法吗?

谢谢!

更新

感谢所有回复,我会尝试提供一些比我在那里提出的概念性内容更具体的内容:

# Import XML Parser
import xml.etree.ElementTree as ET

# Parse XML directly from the file path
tree = ET.parse('xml file')

# Create iterable item list
items = tree.findall('item')

# Create class for historic variables
class DataPoint:
    def __init__(self, low, high, freq):
        self.low = low
        self.high = high
        self.freq = freq

# Create Master Dictionary and variable list for historic variables
masterDictionary = {}

# Loop to assign variables as dictionary keys and associate their values with them
for item in items:
    thisKey = item.find('variable').text
    thisList = []
    masterDictionary[thisKey] = thisList

for item in items:
    thisKey = item.find('variable').text
    newDataPoint = DataPoint(float(item.find('low').text), float(item.find('high').text), float(item.find('freq').text))
    masterDictionary[thisKey].append(newDataPoint)

# Import random module for pseudo-random number generation
import random

diceDictionary = {}

# Dice roll for historic variables
for thisKey in masterDictionary.keys():
    randomValue = random.random()
    diceList = []
    diceList = masterDictionary[thisKey]
    for i in range(len(diceList)):
        if randomValue <= sum(l.freq for l in diceList[0:i+1]):
            diceRoll = random.uniform(diceList[i].low, diceList[i].high)
            diceDictionary[thisKey].append(diceRoll)

我基本上试图创建一个骰子卷字典,以匹配我的主词典的键与数据。我的班级的频率实例是指应用某些箱子的概率,并由骰子卷(随机数)确定。这就是总结的目的。

也许这有助于澄清我的意图?求和示例中的“i”将是某个变量的数据点数。

一旦我在我的输出循环中选择了哪些卷的字典(此处未显示),我将把它应用于下面的代码以使其有意义。

如果我的意图仍然存在任何混淆,请告诉我。我会尝试一些这些建议,但也许有人可以根据我提供的内容将其分解为最简单的形式。

谢谢!

4 个答案:

答案 0 :(得分:7)

你试过了吗?

sum(i.freq for i in items[0:41])

如果您需要最后“i”元素的累积总和,以下是最有效的方法:

sums = [items[0].freq]
for i in items[1:]:
    sums.append(sums[-1] + i.freq)

正如其他海报已经预料到的那样,为变量使用内置函数的名称是一种糟糕的编程风格;我已在上面的代码中将list替换为items

答案 1 :(得分:1)

你的最后一个例子会有二次复杂性。一个更简单的方法就是保持一个总计:

total = 0
for x in list:
    total += x.freq  # total at this point is equal to the sum in your example
# and total at this point is the grand total

如果您不需要列表中每个项目的总和,而只需要总计,请参阅使用sum的{​​{3}}。

此外,list是内置类型,因此您可能不希望将其用作变量名称(这会覆盖内置函数)。

答案 2 :(得分:0)

对于第一个用例,类似

sum(dp.freq for dp in dp_list[:41])

很可能是合适的。

但是如果你想要累积总和,你可以在技术上将它们组合起来,因为总和将是最后的总和。例如,

cumsums = []
for i, dp in enumerate(dp_list):
    if cumsums:
        cumsums.append(dp.freq + cumsums[-1])
    else:
        cumsums.append(dp.freq)

然后cumsums[40]将是前41个DataPoint的频率之和。你甚至可以更多地优化上面的代码(可能用if / else替换try / except IndexError,但重要的是它的正确性。

次要考虑因素

您可能希望使用新式类,而不是

class DataPoint:
你会做的

class DataPoint(object):

此外,您可以在列表切片中删除初始值0,因为lst[:41]lst[0:41]相同,几乎可以用于所有意图和目的。

答案 3 :(得分:0)

  

当列表包含整数时,但我遇到的情况是我有一个类的实例,我需要它们总结。

关键是要理解你不想总结类实例(首先需要定义两个类实例的添加),而是每个的一些freq成员。因此,我们请求sum:实例列表的每个给定实例的.freq的总和。如果我们接受我们需要为列表的实例提供临时名称(以便我们可以访问.freq),那么相应的Python代码尽可能清楚地读取(参见GaretJax的答案)。

您的语法请求子列表的.freq,这当然不存在。