【问题标题】:Python Counter keys() return valuesPython 计数器键()返回值
【发布时间】:2016-01-28 20:42:48
【问题描述】:

我有一个按出现次数排序的计数器。

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).

但是当我做counterlist.keys() 时,返回列表是:

['wirespe', 'four', 'accus',...]

而不是

['they', 'would', 'your',...].

为什么?

【问题讨论】:

  • 如果keys 给你的密钥不在你的Counter 中...你在错误的字典中调用它。
  • python 字典没有排序。 {...} 是一本字典。
  • 我的印象是 OP 偶然得到了一个有序的打印输出,但随后在其上调用 .keys() 结果不同。不幸的是,如上所述,示例不共享单个密钥,因此无法分辨
  • 你的意思是你想要按键的数量吗?为此使用counterlist.most_common()(或[e[0] for e in counterlist.most_common()]

标签: python counter


【解决方案1】:

Counter()

Counter 是一个 dict 子类,用于计算可散列对象。它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。

是一个无序的字典,因此它不会保持您将它们添加到字典中的顺序。如果你想保持它们的顺序,你需要使用OrderedDict()

如果你想要一个OrderedCounter(),那么你可以这样做,我从here 中提取,其中解释了它为什么起作用。

from collections import *

class OrderedCounter(Counter, OrderedDict):
    pass

counterlist = OrderedCounter({'would': 203, 'they': 138, 'your': 134})

print counterlist.keys()

【讨论】:

  • 这是旧的,因为 Python 默认有 dict 顺序。
  • Python 3.6 及更高版本具有 dict 顺序。这是一个很好的回应,详细说明了它。 stackoverflow.com/a/39980744/5012922
  • 这也并不能真正解决 OP 的问题,因为它只保证插入东西的顺序,所以不会按大小顺序返回它们
【解决方案2】:

当您以特定顺序在字典中输入值时,字典不会保留任何顺序。 dict 上的.keys() 不按特定顺序返回。有一个OrderedDict 确实保留了顺序,但我不知道它如何与Counter 交互。

编辑:

您可能想使用Counter.most_common()。这将返回一个 按顺序排列的元组列表。

【讨论】:

    【解决方案3】:

    另一个不创建额外类的解决方案是获取您拥有的一组项目并根据计数的键对它们进行排序。以下代码基于@user3005486:

    import collections
    
    #if this is your list    
    list_to_be_sorted = ['they', 'would', 'they', ...]
    #then counterlist = {'would': 203, 'they': 138, 'your': 134}
    counterlist = collections.Counter(list_to_be_sorted)
    #if you sort this list ascendingly you get ['would', 'would', ..., 'they', 'they', ...etc.]
    sorted_words = sorted(counterlist, key: lambda x:-counterlist[x])
    distinct_words_from_list = set(list_to_be_sorted)
    sorted_distinct_list = sorted(distinct_words_from_list, key: lambda x:-counterlist[x])
    #then sorted_distinct_list = ['would', 'they', 'your']
    

    【讨论】:

    • 啊...-counterlist[x] 排序反转(通过反转)。
    【解决方案4】:

    问题是从 2016 年开始的,同时 Python 中的字典保证保留插入顺序符合 PEP 468

    来自docs

    在 3.7 版中更改:作为dict 的子类,Counter 继承了记住插入顺序的能力。 Counter 对象的数学运算也保持顺序。结果是根据元素在左操作数中第一次遇到的时间排序,然后按照在右操作数中遇到的顺序排序。

    所以,对于 Python >= 3.7

    counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...})
    counterlist.keys()                                                                                                                                           
    # Out: dict_keys(['they', 'would', 'your'])
    

    另见:Are dictionaries ordered in Python 3.6+?

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2020-12-04
      • 1970-01-01
      相关资源
      最近更新 更多