2016-03-15 67 views
0

如何在python中獲取條件元素列表的總和?如何獲得與條件在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 ]) 

回答

2
>>> 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 
相關問題