'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?
Solution 1:[1]
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)
Solution 2:[2]
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 :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | J_H |
| Solution 2 | Amaras |
