本文介绍了如何获取项目的计数格,但保持它们出现的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我需要计算一个单词在列表中出现的次数,不是按频率排序,而是按照单词出现的顺序(即插入顺序)进行计数.

For example, I need to count how many times a word appears in a list, not sorted by frequency but with the order in which the words appear, i.e. insertion order.

from collections import Counter

words = ['oranges', 'apples', 'apples', 'bananas', 'kiwis', 'kiwis', 'apples']

c = Counter(words)

print(c)

所以代替:{'apples': 3, 'kiwis': 2, 'bananas': 1, 'oranges': 1}

我宁愿得到:{'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}

我真的不需要这个Counter方法,任何可以产生正确结果的方法对我来说都是可以的.

And I don't really need this Counter method, any way that will produce correct result is OK for me.

推荐答案

您可以使用:

You can use the recipe that uses collections.Counter and collections.OrderedDict:

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

words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
c = OrderedCounter(words)
print(c)
# OrderedCounter(OrderedDict([('oranges', 1), ('apples', 3), ('bananas', 1), ('kiwis', 2)]))

这篇关于如何获取项目的计数格,但保持它们出现的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:51