2

我熟悉列表的内置 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)

我基本上是在尝试创建一个骰子字典,以将我的主字典的键与数据相匹配。我的类的 freq 实例是指应用某些 bin 的概率,由掷骰子(随机数)确定。这就是求和的目的。

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

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

让我知道是否对我的意图仍有任何困惑。我将尝试其中的一些建议,但考虑到我提供的内容,也许有人可以将其分解为最简单的形式。

谢谢!

4

4 回答 4

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

于 2011-08-03T01:20:19.203 回答
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

如果您不需要列表中每个项目的运行总和,而只需要总计,请参阅GaretJax 的答案,它使用sum.

此外,list它是一种内置类型,因此您可能不想将其用作变量名(这会覆盖内置)。

于 2011-08-03T01:34:17.037 回答
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]是前 41DataPoint秒的频率之和。您甚至可以进一步优化上面的代码(也许将if/替换elsetry/ except IndexError,但重要的是它的正确性。

次要考虑

你可能想使用一个新式的类,所以而不是

class DataPoint:

你会的

class DataPoint(object):

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

于 2011-08-03T01:43:25.787 回答
0

当列表包含整数时,但我的情况是我有一个类的实例,我需要对它们求和。

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

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

于 2011-08-03T02:34:06.827 回答