有几种选择可以制作shallow的副本list
在 Python 3.5+ 中。显而易见的是:
-
some_list.copy()
-
some_list[:]
-
list(some_list)
-
[*some_list]
- 和别的...
哪种方法最快?
NOTE:
虽然这个问题与“列表的副本”相关,但它仅涉及 Python 3.5+ 中的性能。如果您需要“问题的答案”为什么需要 Python 中的列表副本?", or "Python 中列表的浅拷贝和深拷贝有什么区别?“ 阅读以下:如何克隆或复制列表? https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list
这个问题唯一合理的答案是比较它们的执行时间。由于问题涉及 Python 3.5+,我会记得在 Python 3.5 中PEP 448 -- 附加拆包概括 https://www.python.org/dev/peps/pep-0448/被批准了,事实证明[*some_list]
是在 Python 3.5+ 中制作列表浅表副本的最快方法,测量结果如下所示。当然,制作副本的方法还有很多,但我重点介绍以下几种:
-
some_list.copy()
some_list[:]
list(some_list)
[*some_list]
-
from copy import copy; copy(some_list)
Keep in mind these times are relative to one another, but the trend should be similar.
As can be seen from the plot below, all variants behave roughly the same when the len(some_list) >= 1000
:
But at the len(some_list) < 1000
we have a clear winner, and it is [*some_list]
:
测量使用 Python 3.6.3、Windows 7 进行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)