如何以更加pythonic的方式编写以下python代码段(使用python2.7):
typeA = typeB = typeC = 0
for count in counts:
if count['storeType'] == 'dataStore':
typeA = typeA + 1
elif count['storeType'] == 'coverageStore':
typeB = typeB + 1
elif count['storeType'] == 'remoteStore':
typeC = typeC + 1
count_dict = {
'dataStore': dataStore,
'coverageStore': coverageStore,
'remoteStore': remoteStore
}
答案 0 :(得分:2)
您可以使用counter
.kt
行动举例:
from collections import Counter
store_types = [count['storeType'] for count in counts]
print Counter(store_types)
# If you want dict, thought Counter is sub-class of dict. Convert to dict
dict(Counter(store_types))