Pythonic способ заполнить словарь с количеством значений - PullRequest
0 голосов
/ 28 мая 2018

Как мне написать следующий фрагмент 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
    }

1 Ответ

0 голосов
/ 28 мая 2018

Вы можете использовать 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})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...