首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Pythonic式的用值计数填充字典的方法

Pythonic式的用值计数填充字典的方法
EN

Stack Overflow用户
提问于 2018-05-28 18:21:56
回答 1查看 74关注 0票数 1

如何以一种更具python风格的方式(使用python2.7)编写以下python代码段:

代码语言:javascript
复制
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
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 18:45:29

您可以使用counter

代码语言:javascript
复制
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))

操作示例:

代码语言:javascript
复制
In [1]: c = ['a','c','a','c']

In [2]: from collections import Counter

In [4]: Counter(c)
Out[4]: Counter({'a': 2, 'c': 2})
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50564181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档