gpt4 book ai didi

python - 在 Python3.5+ 中制作列表的浅拷贝的最快方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:56 25 4
gpt4 key购买 nike

在 Python 3.5+ 中制作 shallow list 副本有多种选择。最明显的是:

  • some_list.copy()
  • some_list[:]
  • 列表(some_list)
  • [*some_list]
  • 和其他人...

哪种方法最快?

注意:虽然这个问题与“列表的副本”有关,但它仅涉及 Python 3.5+ 中的性能。如果您需要回答“为什么需要 Python 中的列表副本?”或“Python 中列表的浅拷贝和深拷贝有什么区别?”阅读以下内容: How to clone or copy a list?

最佳答案

这个问题唯一合理的答案是比较它们的执行时间。由于问题涉及 Python 3.5+,我会记得在 Python 3.5 中 PEP 448 -- Additional Unpacking Generalizations被批准了,结果是 [*some_list] 是在 Python 3.5+ 中制作列表浅拷贝的最快方法,测量结果如下所示。当然,复制的方法还有很多,但我会重点介绍以下几种:

  • some_list.copy()
  • some_list[:]
  • list(some_list)
  • [*some_list]
  • from copy import copy; copy(some_list)

请记住,这些时间是相对的,但趋势应该是相似的。从下图中可以看出,所有变体在 len(some_list) >= 1000 时表现大致相同。 : enter image description here

但是在 len(some_list) < 1000我们有一个明显的赢家,它是 [*some_list] : enter image description here

测量是使用 Python 3.6.3、Windows 7 进行的。

关于python - 在 Python3.5+ 中制作列表的浅拷贝的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47859482/

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