字典列表中值子集的平均值

2024-09-27 04:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典的清单。我要的是年龄不到25岁的人的平均年龄。在

我知道我的除数是错的,但我不知道如何在理解范围内调整它。在

我得到81/8=10.125。我应该得到81/5=16.2。如何使除数与要添加的元素数匹配?在

people = [{'name': 'John', 'age': 47, 'hobbies': ['Python', 'cooking', 'reading']},
          {'name': 'Mary', 'age': 16, 'hobbies': ['horses', 'cooking', 'art']},
          {'name': 'Bob', 'age': 14, 'hobbies': ['Python', 'piano', 'cooking']},
          {'name': 'Sally', 'age': 11, 'hobbies': ['biking', 'cooking']},
          {'name': 'Mark', 'age': 54, 'hobbies': ['hiking', 'camping', 'Python', 'chess']},
          {'name': 'Alisa', 'age': 52, 'hobbies': ['camping', 'reading']},
          {'name': 'Megan', 'age': 21, 'hobbies': ['lizards', 'reading']},
          {'name': 'Amanda', 'age': 19, 'hobbies': ['turtles']},
          ]


print(float(sum(d['age'] for d in people if d['age'] < 25)) / len(people))

Tags: name元素age字典johnpeople年龄mary
3条回答

我没有在一个列表理解中完成所有操作,而是将其分成两个命令,如下所示:

>>> under_25 = [x['age'] for x in people if x['age'] < 25]
>>> avg_age = sum(under_25)/float(len(under_25))

在一个列表理解中完成所有这些需要你做两次(一次是针对分子的总和,另一次是针对分母中的长度)。我认为这也更具可读性。在

您甚至可以尝试在for循环中执行此操作:

^{pr2}$

最简单的解决方案是结合条件列表理解使用^{}

import numpy as np

>>> np.mean([p['age'] for p in people if 'age' in p and p['age'] < 25])
16.199999999999999

使用纯python解决方案,在计算集合中的每个元素时,应该跟踪总数和计数。这减少了内存占用,因为您不需要存储所有符合条件的值。请注意,我在枚举中使用了生成器。在

^{pr2}$

Python有一个包含^{}函数的^{}模块:

>>> from statistics import mean
>>> mean(d['age'] for d in people if d['age'] < 25)
16.2

或者,如果您有pandas,您可以使用布尔索引:

^{pr2}$

df[df['age'] < 25]只包含年龄小于25的行,['age'].mean()然后计算“age”列的平均值。在

相关问题 更多 >

    热门问题