I am new to python and I am trying to count the number of males and females in a list and that worked but I do not know how to make the average of all the ages in the list.
user_list = [
{'name': 'Alizom_12',
'gender': 'f',
'age': 34,
'active_day': 170},
{'name': 'Xzt4f',
'gender': None,
'age': None,
'active_day': 1152},
{'name': 'TomZ',
'gender': 'm',
'age': 24,
'active_day': 15},
{'name': 'Zxd975',
'gender': None,
'age': 44,
'active_day': 752},
]
def user_stat():
from collections import Counter
counts = Counter((user['gender'] for user in user_list))
print(counts)
user_stat()
>Solution :
def user_stat():
# Here we get rid of the None elements
user_list_filtered = list(filter(lambda x: isinstance(x['age'], int), user_list))
# Here we sum the ages and divide them by the amount of "not-None" elements
print(sum(i.get('age', 0) for i in user_list_filtered) / len(user_list_filtered))
# If you want to divide by None-elements included
print(sum(i.get('age', 0) for i in user_list_filtered) / len(user_list))
user_stat()