Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I get the sum of specific attributes from objects in a list?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading