让我们更好地测量(不仅仅是测量单个执行,也不包括设置),并包含更快的解决方案:
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}
基准代码(在线测试!):
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)
diff_set = set(dict1) - set(dict2)
- decezekeys()
。set(dict)
就可以了。 - Barmardict_1.keys() - dict_2.keys()
将这两个字典看作集合。 - Chris Charley