【发布时间】:2015-10-05 17:46:35
【问题描述】:
str_tuple = "abcd",
a = Counter()
a.update(str_tuple)
但是a[('abcd',)] == 0 因为Counter 计算了'abcd' 字符串,而不是元组。我需要计算元组。
【问题讨论】:
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})
【讨论】: