Bdfy
Bdfy

Reputation: 24719

How to get sum of elements lists with condition in python?

How to get sum of elements lists with condition in python ?

a = [{ "a" : 1 }, {"a" : 1}, { "a" : 3 }, { "a"  : 4 }, { "a" : 5 }, { "a" : 7 }]

def test(d):
    cnt = 0
    for row in d:
        if row["a"] > 1: cnt = cnt + 1
    return cnt


   my variant:

  rr = len( [ 1 for row in a if row["a"] > 1 ] )

Upvotes: 0

Views: 1412

Answers (1)

saikumarm
saikumarm

Reputation: 1575

>>> a = [{ "a" : 1 }, {"a" : 1}, { "a" : 3 }, { "a"  : 4 }, { "a" : 5 }, { "a" : 7 }]    
>>> sum([row['a'] for row in a if row['a'] > 1])
19

Upvotes: 2

Related Questions