Is it possible to turn this code snippet in a list comprehension? How?
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
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.
sum(j for _,i in b.iteritems() for j,_ in i)
will do it.
精彩评论