Python中如何逐个递增Counter计数器,无需每次创建列表调用update
Counter without wrapping it in a list? Great question! Let's break this down clearly:
First off, your current approach using c.update(["foo"]) is totally valid, but I get why creating a single-element list every time feels clunky. The straight answer is: there's no built-in add() method for Counter—the update() method is designed to handle iterables (lists, strings, generators, etc.) rather than individual elements, which is why it doesn't accept a single value directly.
But the good news is you don't have to rely on a custom subclass (unless you want to for readability)! The simplest built-in workaround leverages the fact that Counter is a subclass of dict, so you can use dictionary-style assignment directly:
from collections import Counter c = Counter() c["bar"] += 1 # No list needed at all! print(c) # Output: Counter({'bar': 1})
This works perfectly because Counter automatically initializes missing keys to 0, so you never have to worry about a KeyError even if the element hasn't been counted before.
If you still prefer a more semantic add() method for your codebase (maybe to align with other APIs you're using), your custom subclass approach is totally clean and reasonable:
from collections import Counter class MyCounter(Counter): def add(self, item): self.update([item]) c2 = MyCounter() c2.add("bar") print(c2) # Output: Counter({'bar': 1})
Quick comparison of your options:
c.update(["foo"]): Valid but creates a temporary list (mostly just syntactic noise, minimal performance overhead)c["foo"] += 1: Most concise built-in solution, no extra objects createdMyCounter.add(): Semantically clear, ideal if you're adding single elements frequently and want highly readable code
内容的提问来源于stack exchange,提问作者kuzzooroo

