Python:在lis中求和类实例

2024-09-30 16:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我熟悉用于列表的内置sum()函数,以前也使用过,例如:

sum(list1[0:41])

当我需要一个实例时,我需要从一个类中求出一个整数。在

我上这个班:

^{pr2}$

它们都引用XML文件中的float,这些实例稍后会进入我的代码中的一个列表中。在

例如,我想做的是:

sum(list[0:41].freq)

其中列表包含类实例。在

我还尝试在循环中获取它,这样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实例是指某些箱子被应用的概率,由掷骰子(随机数)决定。这就是总结的目的。在

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

一旦我有了在out循环中选择了哪些rolls的字典(这里没有显示),我将把它应用到下面的代码中,使之更有意义。在

如果对我的意图还有什么疑问,请告诉我。我将尝试这些建议中的一些,但考虑到我所提供的,也许有人可以将其分解为最简单的形式。在

谢谢!在


Tags: 实例textinforrandomfinditemlist
3条回答

对于第一个用例,类似于

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

很可能是合适的。在

但是,如果你想做累计和,你可以技术上把它们结合起来,因为总和就是最后的总和。例如

^{pr2}$

然后cumsums[40]是前41个DataPoint的频率之和。你甚至可以进一步优化上面的代码(也许用try/else替换{}/except IndexError,但重要的是它的正确性。在

次要考虑因素

您可能需要使用一个新样式的类,因此

class DataPoint:

你会的

class DataPoint(object):

另外,您可以在列表切片中删除初始的0,因为lst[:41]与{}在几乎所有的意图和目的上都是相同的。在

最后一个例子的复杂度是二次的。一个简单得多的方法就是保持一个连续的总数:

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's answer,它使用sum。在

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

您是否尝试过:

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

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

^{pr2}$

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

相关问题 更多 >