How to add or increment single item of the Python Counter class

前端 未结 3 592
自闭症患者
自闭症患者 2020-12-30 21:09

A set uses .update to add multiple items, and .add to add a single one.

Why doesn\'t collections.Counter work the same way?

3条回答
  •  感动是毒
    2020-12-30 21:21

    >>> c = collections.Counter(a=23, b=-9)
    

    You can add a new element and set its value like this:

    >>> c['d'] = 8
    >>> c
    Counter({'a': 23, 'd': 8, 'b': -9})
    

    Increment:

    >>> c['d'] += 1
    >>> c
    Counter({'a': 23, 'd': 9, 'b': -9} 
    

    Note though that c['b'] = 0 does not delete:

    >>> c['b'] = 0
    >>> c
    Counter({'a': 23, 'd': 9, 'b': 0})
    

    To delete use del:

    >>> del c['b']
    >>> c
    Counter({'a': 23, 'd': 9})
    

    Counter is a dict subclass

提交回复
热议问题