在Python中,从一组命名元组中获取一个字段的总计数的最简单方法是什么?
在本例中,我要查找的总数 TestResults.failed ,应该是4。这是可行的 for 循环,但感觉还有一种更有效的方法。
TestResults.failed
for
from collections import namedtuple TestResults = namedtuple('TestResults', ['failed', 'attempted']) test_results = [ TestResults(0, 5), TestResults(3, 28), TestResults(1, 7) ] failed_count = 0 for r in test_results: if hasattr(r, 'failed'): failed_count += r.failed print(failed_count)
对于任意对象,可以使用 getattr 具有 0 作为默认值,并使用 sum 用一个 generator expression :
getattr
0
sum
sum(getattr(res, 'failed', 0) for res in test_results)
由于命名元组没有可选值,因此可以直接使用点表示法获取值:
sum(res.failed for res in test_results)
如果您有一个带可选项的命名元组 'failed' 字段,如果可选值为 0 ,则上述操作应该有效,否则,如果可选值为 None ,您可以使用此 0 作为默认值:
'failed'
None
sum(res.failed or 0 for res in test_results)