在字典中设置值,如果没有值?

2024-09-30 06:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用字典来存储一堆计数器,其中每个计数器都在计算文件类型(.wav、.mp3等)的出现次数。在

filetypecounter = {}

当我遇到某个文件类型时,我希望能够以pythonic的方式增加一个计数器。所以我在想。。。在

^{pr2}$

但是,如果文件类型不在字典中,我想将其实例化为1。 所以我的逻辑是,如果filetype counter在那里,那么在counter值上加1,否则设置为1。在

if filetype not in filetypecounter:
    filetypecounter[filetype] = 1
else: 
    filetypecounter[filetype] +=1

有没有更像Python的方式?在


Tags: if字典方式counter计数器not逻辑pythonic
3条回答

看起来您想要的是collections.defaultdict,或者是python2.7及更高版本的collections.Counter。在

from collections import defaultdict

filetypecounter = defaultdict(int)
filetypecounter[filetype] += 1

或者

^{pr2}$

如果您必须使用dict,那么您的解决方案(检查密钥是否存在)是一个合理的解决方案。或许更“Python”的解决方案可能是:

filetypecounter = {}
filetypecounter[filetype] = filetypecounter.get(filetype, 0) + 1

实际上,这和其他建议只是同一主题的变体。我要用柜台。在

很好地使用collections.Counter在这组答案中有很好的介绍,但这可能不是最快的选择。在

一种更古老的方法是:

>>> d={}
>>> for ext in ('.mp3','.mp3','.m4a','.mp3','.wav','.m4a'):
...    d[ext]=d.setdefault(ext,0)+1
... 
>>> d
{'.mp3': 3, '.wav': 1, '.m4a': 2}

这也不是最快的,但比collections.Counter

这些方法有benchmarks,其中defaultdict、try/except或原始方法最快。在

我在这里复制(并扩展)了基准:

^{pr2}$

印刷品:

 defaultdict letters:   3.001 seconds for 100 loops
   defaultdict words:  0.8495 seconds for 100 loops

  setdefault letters:   4.839 seconds for 100 loops
    setdefault words:   0.946 seconds for 100 loops

     Counter letters:   7.335 seconds for 100 loops
       Counter words:   1.298 seconds for 100 loops

        'in' letters:   4.013 seconds for 100 loops
          'in' words:  0.7275 seconds for 100 loops

         try letters:   3.389 seconds for 100 loops
           try words:   1.571 seconds for 100 loops

175,176 letters and 26,630 words

就我个人而言,我很惊讶tryexcept是实现这一目标的最快方法之一。谁知道。。。在

相关问题 更多 >

    热门问题