代码之家  ›  专栏  ›  技术社区  ›  jpp

在python3.7中Counter/defaultdict是如何排序的?

  •  6
  • jpp  · 技术社区  · 7 年前

    我们知道在python3.6中,字典的插入顺序是作为实现细节的,而在3.7中,插入顺序是可以依赖的。

    我希望这也适用于 dict collections.Counter collections.defaultdict . 但这似乎只适用于 defaultdict 案例。

    所以我的问题是:

    1. 是真的维持秩序吗 默认dict 但不是为了 Counter ? 如果是的话,有没有直接的解释?
    2. 你应该订购这些吗 中的子类 collections 依靠 默认dict 有秩序的 在Python 3.7+中?

    以下是我的初步测试:

    命令:命令

    words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
    
    dict_counter = {}
    for w in words:
        dict_counter[w] = dict_counter.get(w, 0)+1
    
    print(dict_counter)
    
    # {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2}
    

    柜台:无序

    from collections import Counter, defaultdict
    
    print(Counter(words))
    
    # Counter({'apples': 3, 'kiwis': 2, 'oranges': 1, 'bananas': 1})
    

    defaultdict:已订购

    dict_dd = defaultdict(int)
    for w in words:
        dict_dd[w] += 1
    
    print(dict_dd)
    
    # defaultdict(<class 'int'>, {'oranges': 1, 'apples': 3, 'bananas': 1, 'kiwis': 2})
    
    1 回复  |  直到 7 年前
        1
  •  11
  •   user2357112    7 年前

    Counter defaultdict 现在都订了,你可以放心了。 只是看起来不整齐,因为 repr 是在dict订购得到保证之前设计的,并且 Counter.__repr__ sorts entries by descending order of value .

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        try:
            items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
            return '%s({%s})' % (self.__class__.__name__, items)
        except TypeError:
            # handle case where values are not orderable
            return '{0}({1!r})'.format(self.__class__.__name__, dict(self))