Paulo Freitas
Paulo Freitas

Reputation: 13649

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

Upvotes: 0

Views: 168

Answers (2)

Gabe
Gabe

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

Edawg
Edawg

Reputation: 258

sum(j for _,i in b.iteritems() for j,_ in i) will do it.

Upvotes: 1

Related Questions