[英]Conditional operations on a list of dictionaries in Python
I'd like to sum the ages of all people in this list of dictionaries, based on a condition on another key (eg Gender == 'male'
): 我想根据另一个键的条件(例如Gender == 'male'
)来总结此词典列表中所有人的年龄:
list_of_dicts= [
{"Name": "Ethan", "Gender": "male", "Age": 11},
{"Name": "Nathan", "Gender": "male", "Age": 6},
{"Name": "Sophie", "Gender": "female", "Age": 14},
{"Name": "Patrick", "Gender": "male", "Age": 11}
]
The following code accomplishes it, but I wonder if there is a more Pythonic/compact way to do it? 以下代码完成了此操作,但我想知道是否还有其他Pythonic / compact方式可以做到这一点? Maybe something like an SQL query for list of dictionaries? 也许像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
How's this? 这个怎么样?
>>> sum(d['Age'] for d in list_of_dicts if d['Gender'] == 'male')
28
Here you are technically calling sum
on a generator expression--one that filters down to dictionaries where Gender
equals "male". 在这里,您从技术上讲是在生成器表达式上调用sum
,该表达式可以过滤成Gender
等于“ male”的字典。
PEP 289 provides an example for some further reading. PEP 289提供了一些进一步阅读的示例。
To find a product rather than a sum: 要查找产品而不是总和:
import numpy as np
np.product([d['Age'] for d in list_of_dicts if d['Gender'] == 'male'])
And if you want to find a product while staying within Python's standard library: 而且,如果您想在使用Python标准库的同时查找产品,请执行以下操作:
from functools import reduce
from operator import mul
reduce(mul, (d['Age'] for d in list_of_dicts if d['Gender'] == 'male'), 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.