我熟悉列表的内置 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”将是某个变量的数据点数。
一旦我有了在我的输出循环中选择了哪些卷的字典(此处未显示),我将把它应用到下面的代码中以使一些有意义的东西。
让我知道是否对我的意图仍有任何困惑。我将尝试其中的一些建议,但考虑到我提供的内容,也许有人可以将其分解为最简单的形式。
谢谢!