Home > front end >  How do I get the sum of specific attributes from objects in a list?
How do I get the sum of specific attributes from objects in a list?

Time:04-17

I have a list of "Tile" objects with attributes defined as such:

class Tile:

    def __init__(self, water, soil):
        self.water = water
        self.soil = soil
    

Lake = Tile(20, 0)
Dirt = Tile(0, 10)
Tree = Tile(-5, -5)

These objects fill the following list:

environment = [Dirt, Tree, Lake, Dirt, Dirt]

Is there a way for me to get the total sum of .water and .soil for all objects in the list?

CodePudding user response:

Add up the waters:

sum(tile.water
    for tile in environment)

Similarly for soil values:

sum(tile.soil
    for tile in environment)

It's unclear if you wanted them combined:

sum(tile.water   tile.soil
    for tile in environment)

CodePudding user response:

For your question, one of the first things that comes to mind is to loop through your collection and get the soil and water values like so:

soil = water = 0
for tile in environment:
    soil  = tile.soil
    water  = tile.water

If you want to have both combined, simply modify the code by removing a variable and adding both tile.soil and tile.water to the combined sum.

There are more advanced ways to do it, using the sum function like in J_H's answer, or even using map and operator.attrgetter shenanigans, but it's not really worth it at your level of Python proficiency seems to be.

Hope this helped :)

  • Related