【问题标题】:How are Counter / defaultdict ordered in Python 3.7?在 Python 3.7 中 Counter / defaultdict 如何排序?
【发布时间】:2018-09-04 21:34:56
【问题描述】:

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

我预计dict 的子类也会出现这种情况,例如collections.Countercollections.defaultdict。但这似乎只适用于defaultdict 案例。

所以我的问题是:

  1. 是否确实为defaultdict 维护了排序,但为Counter 维护了排序?如果有,是否有简单的解释?
  2. 是否应该将collections 模块中的这些dict 子类的排序视为实现细节?或者,例如,我们能否依靠 defaultdict 像 Python 3.7+ 中的 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:有序

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

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

    【讨论】:

    • 这太棒了。补充一下,list(Counter(words)) 可以简单地测试这个,即插入顺序将被返回。谢谢!
    猜你喜欢
    • 2012-04-28
    • 2015-03-04
    • 1970-01-01
    • 2016-08-16
    • 2021-06-26
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    相关资源
    最近更新 更多