str_tuple = "abcd",
a = Counter()
a.update(str_tuple)
但是 a[('abcd',)] == 0
因为 Counter
计算的是 'abcd'
字符串,而不是元组。我需要计算元组的数量。
最佳答案
Counter.update()
需要一个序列来进行计数。如果您需要对元组进行计数,请将该值放入序列中,然后再将其传递给 Counter.update()
方法:
a.update([str_tuple])
或使用:
a[str_tuple] += 1
将该元组的计数加一。
演示:
>>> from collections import Counter
>>> str_tuple = "abcd",
>>> a = Counter()
>>> a.update([str_tuple])
>>> a
Counter({('abcd',): 1})
>>> a = Counter()
>>> a[str_tuple] += 1
>>> a
Counter({('abcd',): 1})
关于用于计数器的 Python 元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954725/