gpt4 book ai didi

python - 从 python 中的字典获取键列表/键集的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-05 01:51:53 27 4
gpt4 key购买 nike

为了快速比较 2 个字典的键,我使用这种方法创建键集:

dict_1 = {"file_1":10, "file_2":20, "file_3":30, "file_4":40}
dict_2 = {"file_1":10, "file_2":20, "file_3":30}
set_1 = {file for file in dict_1}
set_2 = {file for file in dict_2}

然后我使用 diff_set = set_1 - set_2 来查看 set_2 中缺少哪些键。

有没有更快的方法?我发现使用 set(dict.keys()) 不太有效,所以我会改用它 - 但它更有效吗?

最佳答案

让我们更正确地衡量(不仅仅是衡量单个执行,也不包括设置)并包括更快的解决方案:

300 ns  300 ns  300 ns  {*dict_1} - {*dict_2}
388 ns 389 ns 389 ns {file for file in dict_1 if file not in dict_2}
389 ns 390 ns 390 ns dict_1.keys() - dict_2
458 ns 458 ns 458 ns set(dict_1) - set(dict_2)
472 ns 472 ns 472 ns dict_1.keys() - dict_2.keys()
665 ns 665 ns 668 ns set(dict_1.keys()) - set(dict_2.keys())
716 ns 716 ns 716 ns {file for file in dict_1} - {file for file in dict_2}

基准代码(Try it online!):

import timeit

setup = '''
dict_1 = {"file_1":10, "file_2":20, "file_3":30, "file_4":40}
dict_2 = {"file_1":10, "file_2":20, "file_3":30}
'''

codes = [
'{file for file in dict_1} - {file for file in dict_2}',
'set(dict_1) - set(dict_2)',
'set(dict_1.keys()) - set(dict_2.keys())',
'dict_1.keys() - dict_2',
'dict_1.keys() - dict_2.keys()',
'{*dict_1} - {*dict_2}',
'{file for file in dict_1 if file not in dict_2}',
]

exec(setup)
for code in codes:
print(eval(code))

tss = [[] for _ in codes]
for _ in range(20):
print()
for code, ts in zip(codes, tss):
number = 10000
t = min(timeit.repeat(code, setup, number=number)) / number
ts.append(t)
for code, ts in sorted(zip(codes, tss), key=lambda cs: sorted(cs[1])):
print(*('%3d ns ' % (t * 1e9) for t in sorted(ts)[:3]), code)

关于python - 从 python 中的字典获取键列表/键集的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71913816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com