【问题标题】:How to sort counter by alphabetical order THEN by value order in Python如何按字母顺序对计数器进行排序然后在 Python 中按值顺序排序
【发布时间】:2017-07-12 01:56:53
【问题描述】:

我有一个计数器,我想按以下方式排序:

Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'd': 1, 'T': 1})

当我使用我的代码时,它给了我以下信息:

Counter({'M': 9, 'P': 5, 'L': 5, 'S': 2, 'T': 1, 'd': 1})

我尝试了sorted()函数,但是当我使用它时,它的返回值不再是一个计数器了。

这是我的代码,你会怎么做?

def most_encountered_letters(dictionnary):
    counter = collections.Counter()
    for line in dictionnary:
        words = line.split(',')[0].split(' ')
        for word in words:
            counter[word[0]] += 1

    print(counter)                                                                                                        
    return counter.most_common(5)

【问题讨论】:

  • A CounterDict 子类,因此根据定义它是未排序的,如果您尝试使用 sorted() 它必须返回非Dict 类。您可以将结果移动到OrderedDict。我想,但我的问题是“你为什么要排序?”,因为您的实际问题可能会以另一种方式更好地解决。最后,这是lots of ways to sort。顺便说一句,Python 2.x 还是 3.x?
  • 在python中无法对Dict进行排序,唯一的方法是查看链接stackoverflow.com/questions/613183/…
  • 要精确!您的 not-an-answer 彻底改变了您的问题,并使两个答案都无效。
  • 另外,edit 你的头衔。你的标题说你想先按键排序,然后按值排序,但听起来你实际上想先按值排序,然后按键排序,这是相反的。

标签: python sorting counter


【解决方案1】:

Counters 是无序的。它们是dict 的子类,与dict 一样,没有排序。说“a sorted Counter”是没有意义的。您可以获取Counter 中按您想要的方式排序的项目列表,例如:

>>> from collections import Counter
>>> c = Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'd': 1, 'T': 1})
>>> c
Counter({'M': 9, 'L': 5, 'P': 5, 'S': 2, 'T': 1, 'd': 1})
>>> sorted(c.items(), key= lambda t: (t[1], t[0]), reverse=True)
[('M', 9), ('P', 5), ('L', 5), ('S', 2), ('d', 1), ('T', 1)]

如果你想要一个有序的Mapping 类型,你要么必须使用内置的OrderedDict,要么实现你自己的。我们可以使用多重继承来重用内置类来获得我们想要的东西。这是食谱straight from the docs

class OrderedCounter(Counter, OrderedDict):
    'Counter that remembers the order elements are first encountered'

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))

    def __reduce__(self):
        return self.__class__, (OrderedDict(self),)

所以,在行动中:

>>> oc = OrderedCounter()
>>> for k,v in sorted(c.items(), key= lambda t: (t[1], t[0]), reverse=True):
...     oc[k] = v
...
>>> oc
OrderedCounter(OrderedDict([('M', 9), ('P', 5), ('L', 5), ('S', 2), ('d', 1), ('T', 1)]))
>>> for k,v in oc.items():
...   print(k,v)
...
M 9
P 5
L 5
S 2
d 1
T 1
>>>

更重要的是,您应该考虑为什么需要订购的Counter...您真的需要吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多