【问题标题】:collections.Counter ordered as appear in listcollections.Counter 按列表中的顺序排列
【发布时间】:2019-08-21 14:55:25
【问题描述】:

是否可以按列表顺序打印?

lis=['c','b','c','a','b','b']
collections.Counter(lis)

计数器{'b':3,'c':2,'a':1}

但我想要的是:

计数器{'c':2,'b':3,'a':1}

【问题讨论】:

  • 先 c 然后 b 然后 a

标签: python counter


【解决方案1】:

这可以解决问题:

from collections import Counter, OrderedDict

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

lis=['c','b','c','a','b','b']
print(OrderedCounter(lis))
#OrderedCounter(OrderedDict([('c', 2), ('b', 3), ('a', 1)]))

来自this related question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2019-01-08
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2022-06-24
    相关资源
    最近更新 更多