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)
sum(i.failed for i in test_results)
?hasattr(r, 'failed')
in your for loop?hasattr()
because in reality the named tuple comes from a 3rd party module, and I wanted to be sure I didn't get any errors if the field I was checking didn't exist. I've since inspected that module and can see that the field is required anyway, so the check is irrelevant and thus not required. Thanks.