我使用字典来存储一堆计数器,其中每个计数器都在计算文件类型(.wav、.mp3等)的出现次数。在
filetypecounter = {}
当我遇到某个文件类型时,我希望能够以pythonic的方式增加一个计数器。所以我在想。。。在
^{pr2}$但是,如果文件类型不在字典中,我想将其实例化为1。 所以我的逻辑是,如果filetype counter在那里,那么在counter值上加1,否则设置为1。在
if filetype not in filetypecounter:
filetypecounter[filetype] = 1
else:
filetypecounter[filetype] +=1
有没有更像Python的方式?在
看起来您想要的是collections.defaultdict,或者是python2.7及更高版本的collections.Counter。在
或者
^{pr2}$如果您必须使用
dict
,那么您的解决方案(检查密钥是否存在)是一个合理的解决方案。或许更“Python”的解决方案可能是:实际上,这和其他建议只是同一主题的变体。我要用柜台。在
很好地使用
collections.Counter
在这组答案中有很好的介绍,但这可能不是最快的选择。在一种更古老的方法是:
这也不是最快的,但比
collections.Counter
快这些方法有benchmarks,其中defaultdict、try/except或原始方法最快。在
我在这里复制(并扩展)了基准:
^{pr2}$印刷品:
就我个人而言,我很惊讶
try
except
是实现这一目标的最快方法之一。谁知道。。。在相关问题 更多 >
编程相关推荐