In Python, what is the easiest way to get the total count of one field from a set of named tuples?
In this example, I'm looking for the total count of TestResults.failed, which should be 4. It's doable with a for loop, but it feels like there could be a more efficient way.
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)
With arbitrary objects, you can use
getattrwith0as a default value, and usesumwith a generator expression:Since you have namedtuples with no optional values, you can get the values directly using dot notation:
If you have a namedtuple with an optional
'failed'field, if the optional value is0, then the above should work, otherwise, if the optional value isNone, you could use this to use0as a default value: