Python中字典列表上的条件操作
我想根据另一个键上的条件(例如,Python中字典列表上的条件操作,python,json,list,dictionary,Python,Json,List,Dictionary,我想根据另一个键上的条件(例如,Gender==“male”)计算字典列表中所有人的年龄总和: 下面的代码实现了这一点,但我想知道是否有一种更为python/compact的方法来实现这一点?可能类似于对字典列表的SQL查询 total_male_age = 0 for dict in list_of_dicts: if dict.get("Gender") == "male": total_male_age = total_male_age + dict.get("
Gender==“male”
)计算字典列表中所有人的年龄总和:
下面的代码实现了这一点,但我想知道是否有一种更为python/compact的方法来实现这一点?可能类似于对字典列表的SQL查询
total_male_age = 0
for dict in list_of_dicts:
if dict.get("Gender") == "male":
total_male_age = total_male_age + dict.get("Age")
#total_male_age = 28
这个怎么样
>>> sum(d['Age'] for d in list_of_dicts if d['Gender'] == 'male')
28
在这里,从技术上讲,您是在一个生成器表达式上调用sum
,该表达式可以过滤到Gender
等于“male”的字典
为进一步阅读提供了一个示例
要查找乘积而不是总和,请执行以下操作:
import numpy as np
np.product([d['Age'] for d in list_of_dicts if d['Gender'] == 'male'])
如果您想在Python的标准库中查找产品:
from functools import reduce
from operator import mul
reduce(mul, (d['Age'] for d in list_of_dicts if d['Gender'] == 'male'), 1)
from functools import reduce
from operator import mul
reduce(mul, (d['Age'] for d in list_of_dicts if d['Gender'] == 'male'), 1)