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

前端 未结 3 587
自闭症患者
自闭症患者 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:29

    There is a more Pythonic way to do what you want:

    c = Counter(item.property for item in something if item.has_some_property)
    

    It uses a generator expression instead of open-coding the loop.

    Edit: Missed your no-list-comprehensions paragraph. I still think this is the way to actually use Counter in practice. If you have too much code to put into a generator expression or list comprehension, it is often better to factor that into a function and call that from a comprehension.

提交回复
热议问题