加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何获取项目的计数字典,但保持它们出现的顺序?

发布时间:2020-12-20 12:24:36 所属栏目:Python 来源:网络整理
导读:例如,我需要计算一个单词出现在列表中的次数,不是按频率排序,而是按照单词出现的顺序排序,即插入顺序. from collections import Counterwords = ['oranges','apples','bananas','kiwis','apples']c = Counter(words)print(c) 因此,而不是:{‘apples’:3,’
例如,我需要计算一个单词出现在列表中的次数,不是按频率排序,而是按照单词出现的顺序排序,即插入顺序.

from collections import Counter

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

c = Counter(words)

print(c)

因此,而不是:{‘apples’:3,’kiwis’:2,’香蕉’:1,’橘子’:1}

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

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

解决方法

您可以使用使用collections.Counter和collections.OrderedDict的 recipe:

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","bananas","kiwis","apples"]
c = OrderedCounter(words)
print(c)
# OrderedCounter(OrderedDict([('oranges',1),('apples',3),('bananas',('kiwis',2)]))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读