使用字符串而不是字母更新 python 中的计数器集合

Update Counter collection in python with string, not letter

如何用字符串而不是字符串的字母来更新计数器? 例如,在用两个字符串初始化此计数器后:

from collections import Counter
c = Counter(['black','blue'])

"add" 到另一个字符串,例如 'red'。当我使用 update() 方法时,它会添加字母 'r'、'e'、'd':

c.update('red')
c
>>Counter({'black': 1, 'blue': 1, 'd': 1, 'e': 1, 'r': 1})

您可以使用字典更新它,因为添加另一个字符串与使用计数 +1 更新密钥相同:

from collections import Counter
c = Counter(['black','blue'])

c.update({"red": 1})  

c
# Counter({'black': 1, 'blue': 1, 'red': 1})

如果key已经存在,则计数加一:

c.update({"red": 1})

c
# Counter({'black': 1, 'blue': 1, 'red': 2})
c.update(['red'])
>>> c
Counter({'black': 1, 'blue': 1, 'red': 1})

Source can be an iterable, a dictionary, or another Counter instance.

虽然字符串是可迭代的,但结果不是您所期望的。先转为列表、元组等

您可以使用:

c["red"]+=1
# or
c.update({"red": 1})
# or 
c.update(["red"])

无论密钥是否存在,所有这些选项都将起作用。如果存在,他们会将计数增加 1

试试这个:

c.update({'foo': 1})

虽然我也可以举另一个例子,你可以增加和减少计数

from collections import Counter

counter = Counter(["red", "yellow", "orange", "red", "orange"])
# to increase the count
counter.update({"yellow": 1})
# or
counter["yellow"] += 1

# to decrease
counter.update({"yellow": -1})
# or
counter["yellow"] -= 1

我最近 运行 遇到了同样的问题。你也可以把它放在这样的元组中。

c.update(('red',))

以前的答案没有建议这个替代方案,所以我不妨post在这里。