您的位置:首页 > 编程语言 > Python开发

python 合并字典效率问题

2015-03-25 15:04 239 查看
原文地址: http://www.dewen.io/q/2002
x
=
{'a':1,
'b':
2}
;

y
=
{'b':10,
'c':
11}

//方法一

z
= dict(x.items()+y.items());

//方法二

z
= dict(z,**y)

//方法三

z
= x.copy()

z.update(y)

//方法四

z
=
(lambda
a, b:
(lambda
a_copy: a_copy.update(b)
or a_copy)(a.copy()))(x,
y)

In [17]: timeit.timeit("dict(x,**y)", "x
= {'a':1, 'b': 2};y={'b':10, 'c':11}")

Out[17]: 0.6188690662384033

In [18]: timeit.timeit("dict(x.items()+y.items())", "x
= {'a':1, 'b': 2};y={'b':10, 'c':11}")

Out[18]: 1.8446910381317139

In [19]: timeit.timeit("dict(x,**y)", "x
= {'a':1, 'b': 2};y={'b':10, 'c':11}")

Out[19]: 0.6554520130157471

In [20]: timeit.timeit("z=x.copy();z.update(y)", "x
= {'a':1, 'b': 2};y={'b':10, 'c':11}")

Out[20]: 0.5006368160247803

In [21]: timeit.timeit("(lambda
a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)", "x = {'a':1, 'b': 2};y={'b':10, 'c':11}")

Out[21]: 1.0203309059143066
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: