2017-02-17 60 views
2

我的字典清單:問題得到計數

d = [{'status': u'Working', 'name': u'AR000001'}, {'status': u'Working', 'name': u'AR000002'}, {'status': u'Working', 'name': u'AR000003'},{'status': u'Working', 'name': u'AR000013'}] 

我想用狀態鍵

我想這使用for循環這裏算工作的項目,這是工作的罰款:

print "total",len(d) 
wcount = 0 

for i in d: 
    if i['status'] == "Working": 
    wcount += 1 


print "working count",wcount 

但我使用列表理解失去了一些東西:

count = [sum(li) for li in d if li['status'] == 'Working'] 
print count 

錯誤:

count = [sum(li) for li in d if li['status'] == 'Working'] 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

回答

5

隨着sum(li),你試圖將字典鍵添加到由sum提供的默認INT 0元起拍值;字典將自然迭代時提供它們的密鑰。

可以從比較,這是很容易強制爲1 True或0 False bool值改爲適用總和:

count = sum(li['status'] == 'Working' for li in d) 
+0

哦......簡單的列表。謝謝,我的併發症很嚴重。幾個小時後我會接受答案。再次感謝 –

+0

好的解決方案m8。 – ospahiu

1

將大致相當於下面的環:

count = sum([1 for li in d if li['status'] == 'Working']) 

由於li將被分配給與原始數據結構相匹配的每個元素,因此會出現上述錯誤

2

單個內襯。

>>> sum(1 for dictionary in dictionaries if dictionary['status'] == 'Working') 
4 

reduce替代(一個通)。

>>> print reduce(lambda count, dictionary: count + (dictionary['status'] == 'Working'), dictionaries, 0) 
4