【问题标题】:Pythonic way to iterate over a collections.Counter() instance in descending order?以降序遍历 collections.Counter() 实例的 Pythonic 方式?
【发布时间】:2012-06-17 17:12:13
【问题描述】:

在 Python 2.7 中,我想以降序遍历 collections.Counter 实例。

>>> import collections
>>> c = collections.Counter()
>>> c['a'] = 1
>>> c['b'] = 999
>>> c
Counter({'b': 999, 'a': 1})
>>> for x in c:
        print x
a
b

在上面的示例中,元素似乎按照它们添加到 Counter 实例的顺序进行迭代。

我想从最高到最低遍历列表。我看到 Counter 的字符串表示是这样做的,只是想知道是否有推荐的方法。

【问题讨论】:

    标签: collections iteration python-2.7 python


    【解决方案1】:

    您可以遍历c.most_common() 以按所需顺序获取项目。另请参阅documentation of Counter.most_common()

    例子:

    >>> c = collections.Counter(a=1, b=999)
    >>> c.most_common()
    [('b', 999), ('a', 1)]
    

    【讨论】:

      【解决方案2】:

      以下是在 Python 集合中迭代 Counter 的示例:

      >>>def counterIterator(): 
      ...  import collections
      ...  counter = collections.Counter()
      ...  counter.update(('u1','u1'))
      ...  counter.update(('u2','u2'))
      ...  counter.update(('u2','u1'))
      ...  for ele in counter:
      ...    print(ele,counter[ele])
      >>>counterIterator()
      u1 3
      u2 3
       
      

      【讨论】:

        【解决方案3】:

        仅返回降序即可解决您的问题,但这里是通用的方法。万一其他人从谷歌来到这里,这就是我必须解决的问题。基本上,您上面所拥有的内容会返回 collections.Counter() 中字典的键。要获取值,您只需将键传递回字典,如下所示:

        for x in c:
            key = x
            value = c[key]
        

        我遇到了一个更具体的问题,我需要计算字数并希望过滤掉低频的字数。这里的技巧是复制 collections.Counter() 或者当你尝试从字典中删除它们时,你会得到“RuntimeError: dictionary changed size during iteration”。

        for word in words.copy():
            # remove small instance words
            if words[word] <= 3:
                del words[word]
        

        【讨论】:

          猜你喜欢
          • 2022-01-08
          • 1970-01-01
          • 1970-01-01
          • 2016-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-15
          • 1970-01-01
          相关资源
          最近更新 更多