如何在Python 3.7中订购Counter / defaultdict?

问题描述 投票:6回答:1

我们知道在Python 3.6中,字典是作为实现细节排序的插入,并且可以依赖3.7插入顺序。

我期望dict的子类如collections.Countercollections.defaultdict也是如此。但这似乎只适用于defaultdict案。

所以我的问题是:

  1. defaultdict的订购是否正确,但是Counter没有订购?如果是这样,是否有直接的解释?
  2. dict模块中这些collections子类的排序是否应被视为实现细节?或者,例如,我们可以依靠defaultdict在Python 3.7+中像dict一样进行插入排序吗?

以下是我的基本测试:

dict:有序

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:ordered

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})
python python-3.x dictionary counter defaultdict
1个回答
8
投票

Counterdefaultdict现在都订购了,您可以信赖它。 Counter看起来并不是因为它的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))
© www.soinside.com 2019 - 2024. All rights reserved.