如何以一种更具python风格的方式(使用python2.7)编写以下python代码段:
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
}
发布于 2018-05-28 18:45:29
您可以使用counter
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))
操作示例:
In [1]: c = ['a','c','a','c']
In [2]: from collections import Counter
In [4]: Counter(c)
Out[4]: Counter({'a': 2, 'c': 2})
https://stackoverflow.com/questions/50564181
复制相似问题