用于计数器的 Python 元组

标签 python tuples counter

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/

相关文章:

java - elasticsearch - 增加计数器或创建文档(如果不存在)

python - 如何在 python 中拆分具有多个条件的字符串?

Python 子类

python - 给定一个文件,返回一个元组列表,表示 Python 文件中的行

php - 如何在 foreach 迁移表中使用计数器? (拉拉维尔 5.3)

ruby-on-rails - Rails 中页面浏览量的简单点击计数器

python - 在 Mac OS X 上安装 MySQL Python

python - 加载 TrueType 字体到 OpenCV

python 在 where 子句中使用元组或数组

python - for 循环如何在元组中工作