Search code examples
pythonclasslistsuminstances

Python: Summing class instances inside a list


I am familiar with the built-in sum() function for lists and have used it before, eg:

sum(list1[0:41])

when the list contains integers, but I'm in a situation where I have instances from a Class and I need them summed.

I have this Class:

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

They all refer to floats from an XML file and these instances later go into a list in my code.

So for instance, I want to be able to do something like:

sum(list[0:41].freq)

where the list contains the Class instances.

I'm also trying to get it in a loop so that the second number in the range of the sum() goes up each time, eg:

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

Anyone know how I can get around this or if there is another way to do it?

Thanks!

UPDATE:

Thanks for all the responses, I'll try to provide something more concrete than the conceptual stuff I put up there first:

# 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 am basically trying to create a dictionary of dice rolls to match the keys of my master dictionary with the data. The freq instance of my Class refers to probabilities of certain bins being applied and are determined by a dice roll (random number). This is what the summing is for.

Maybe this helps clear up my intention? The "i" in the summing example will be whatever the number of data points for a certain variable.

Once I have the dictionaries of which rolls were selected in my out loop (not shown here), I'll apply it to code below to make something meaningful.

Let me know if there is still any confusion about my intention. I will try a few of these suggestions out, but maybe someone can break it down to the simplest form considering what I've provided.

Thanks!


Solution

  • Have you tried:

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

    If you need the cumulative sum of the last "i" elements, the following is the most efficient approach:

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

    As other posters already have anticipated, it is a bad programming style to use name of builtins for your variables; I have replace list with items in the code above.