【问题标题】:Python tuple for Counter计数器的 Python 元组
【发布时间】:2015-10-05 17:46:35
【问题描述】:
str_tuple = "abcd",
a = Counter()  
a.update(str_tuple)

但是a[('abcd',)] == 0 因为Counter 计算了'abcd' 字符串,而不是元组。我需要计算元组。

【问题讨论】:

    标签: python tuples counter


    【解决方案1】:

    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})
    

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多