我们知道在Python 3.6中,字典将插入顺序作为实现细节,而在3.7中,则可以依赖插入顺序。
我希望dict
的子类(例如collections.Counter
和collections.defaultdict
)也是如此。但这似乎只对defaultdict
情况成立。
所以我的问题是:
是否确实为defaultdict
而不是Counter
维持顺序?而且,如果是这样,是否有一个简单的解释?
这些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:有序
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})
参考方案
Counter
和defaultdict
现在都已订购,您可以依靠它。 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))
Python ThreadPoolExecutor抑制异常 - pythonfrom concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…
如何在Python Tkinter中管理带边框标签内的间距? - python我有一个程序,其中我制作了带边框的标签,但其带边框的位置太接近文本。我想在“边框”和“标签文本”之间给出间距。代码如下。from tkinter import * import tkinter as tk win = Tk() win.title("Labels") win.geometry("800x600+50+50…
在返回'Response'(Python)中传递多个参数 - python我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…
Python exchangelib在子文件夹中读取邮件 - python我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…
R'relaimpo'软件包的Python端口 - python我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。