Reputation: 13649
a = 0 b = {'a': [(1, 'a'), (2, 'b'), (3, 'c')], 'b': [(4, 'd'), (5, 'e')]} for c, d in b.iteritems(): for e, f in d: a += e // now a = 15
Tried several ways. I want to know a way (if possible) to simplify this sum with a list comprehension:
a = sum(...)
Thank you in advance, pf.me
Upvotes: 0
Views: 168
Reputation: 86718
a = sum(e for d in b.itervalues() for e, _ in d)
works in Python 2.7.
a = sum([e for d in b.itervalues() for e, _ in d])
works in Python 2.3.
I haven't tried it, but a = sum(e for d in b.values() for e, _ in d)
should be the Python 3.0 equivalent.
Upvotes: 6