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

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

    Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with Counter.

    c = Counter()
    for item in something:
        if item.has_some_property:
            c[item.property] += 1
        elif item.has_some_other_property:
            c[item.other_property] += 1
        elif item.has_some.third_property:
            c[item.third_property] += 1
    

提交回复
热议问题