gpt4 book ai didi

python - 字典键数

转载 作者:行者123 更新时间:2023-12-01 04:16:07 25 4
gpt4 key购买 nike

在 Python 2.7 中:我正在测量一个对函数返回的字典的键进行计数的过程。

显示了一个基本示例,其中函数 getList() 返回一个字符列表,可能是 ['a']、['b']、['c'] 或 ['d' '];大多数列表都是单个元素,尽管有时可能会返回两个元素,例如['广告']。我想统计所有退回的东西。我想到的一种方法如下所示:

    myDict = {'a':0, 'b':0, 'c':0, 'd':0, 'error':0, 'total':0}
for key in charList:
myDict[key] += 1
myDict['total'] += 1

有没有一种更Pythonic的方式,也许是字典理解来计算列表(不同长度)中的键?

import random

def getList():
'''mimics a prcoess that returns a list of chars between a - d
[most lists are single elements, though some are two elements]'''
number = (random.randint(97,101))
if number == 101:
charList = [chr(number-1), chr(random.randint(97,100))]
if charList[0] == charList[1]:
getList()
else:
charList = [chr(number)]
return charList


myDict = {'a':0, 'b':0, 'c':0, 'd':0, 'error':0, 'total':0}

for counter in range(0,5):
charList = getList()
for key in charList:
print charList, '\t', key
try:
myDict[key] += 1
myDict['total'] += 1
except:
myDict['error'] += 1

print "\n",myDict

生成的输出:

Output

最佳答案

您可以使用内置的collections.Counter类:https://docs.python.org/2/library/collections.html#collections.Counter

例如您的代码:

import collections
ctr = collections.Counter()

for ii in range(0,5):
charList = getList()
ctr.update(charList)

ctr['total'] = sum(ctr.values())
print ctr

这将打印:

Counter({'total': 7, 'd': 5, 'a': 1, 'c': 1})

关于python - 字典键数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34288894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com