Reputation: 15
Hello I want to find the sum of everything inside a list, however when I look it up they show examples of numbers inside lists. But I have classes inside lists.
Here is dogclass.py
class dog:
def __init__(self,name,age):
self.name = name
self.age = age
Here is dogs.py (I made dogs.py so I dont have to define all these dogs I will make on my main file)
from dogclass import dog
baba = dog("Baba", 8)
jojo = dog("Jojo", 3)
And here is main.py
import dogs as d
dogs = [d.baba, d.jojo]
average_combine = dogs[0].age + dogs[1].age
dogs_age_average = round(average_combine / len(dogs))
This code works just fine and I could do it this way But If i have a hundred dogs, I will have to do this a hundred times And I don't want to do that. Is there a way that I can find the sum of the ages without having to do this?
Upvotes: 0
Views: 68
Reputation: 36
If sum:
sum(d.age for d in dogs)
If average, better make it float if not want to lose digits after integer:
sum(float(d.age) for d in dogs)/len(dogs)
Upvotes: 0
Reputation: 21
i think this code will help you to do that easily.
class dog:
def __init__(self,name,age):
self.name = name
self.age = age
# creating list
list = []
# appending instances to list
list.append( dog('a', 40) )
list.append( dog('b', 40) )
list.append( dog('c', 44) )
list.append( dog('x', 50) )
average_combine= 0
for obj in list:
average_combine=+ obj.age
dogs_age_average = round(average_combine / len(list))
print(dogs_age_average)
Upvotes: 0
Reputation: 174690
Use a generator expression (a list comprehension without the list-materialization step) to grab the age
value from each object in the list, then sum the resulting list:
age_sum = sum(d.age for d in dogs)
Upvotes: 2
Reputation: 81
One line solution, you probably want to read up on Python's list comprehensions
dogs_age_average = round(sum(dog.age for dog in dogs) / len(dogs))
Upvotes: 0
Reputation: 39
You could use a list comprehension to sum up all the dog's ages:
class dog:
def __init__(self,name,age):
self.name = name
self.age = age
baba = dog("Baba", 8)
jojo = dog("Jojo", 3)
dogs = [baba, jojo]
average_combine = sum([d.age for d in dogs])
dogs_age_average = round(average_combine / len(dogs))
print(dogs_age_average)
Result:
6
Upvotes: 0