1
str_tuple = "abcd",
a = Counter()
a.update(str_tuple)
但a[('abcd',)] == 0
因为Counter
计数'abcd'
字符串,而不是元组。我需要计算元组。Python的元组计数器
str_tuple = "abcd",
a = Counter()
a.update(str_tuple)
但a[('abcd',)] == 0
因为Counter
计数'abcd'
字符串,而不是元组。我需要计算元组。Python的元组计数器
Counter.update()
需要一个序列的东西来算。如果你需要算一个元组,这个值放到一个序列将它传递给Counter.update()
方法之前:
a.update([str_tuple])
或使用:
a[str_tuple] += 1
增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})