如何获得项目的计数字典但保持它们出现的顺序? [英] How to get count dict of items but maintain the order in which they appear?

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

问题描述

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

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.

推荐答案

您可以使用 recipe 使用 collections.Countercollections.OrderedDict:

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆