python 列表副本 : is there a difference between old[:] and list(old)?

标签 python

old = [1, 2, 3]

下面两行有什么区别(如果有的话)?

new = old[:]
new = list(old)

更新 我已经接受了 ubershmekel 的回答,但后来我了解到一个有趣的事实:[:] 对于小列表(10 个元素)更快但是 list() 对于更大的列表(100000 个元素)更快。

~$ python -S -mtimeit -s "a = list(range(10))" "a[:]"
1000000 loops, best of 3: 0.198 usec per loop
~$ python -S -mtimeit -s "a = list(range(10))" "list(a)"
1000000 loops, best of 3: 0.453 usec per loop
~$ python -S -mtimeit -s "a = list(range(100000))" "a[:]"
1000 loops, best of 3: 675 usec per loop
~$ python -S -mtimeit -s "a = list(range(100000))" "list(a)"
1000 loops, best of 3: 664 usec per loop

最佳答案

如果 old 不是列表,old[:] 将是与 old 相同类型容器(可能是元组或字符串)中的 old 的所有元素,而 list(old) 将是具有相同容器的列表元素。

即如果 old 是字符串 'foo',old[:] 将是字符串 'foo',而 list(old) 将是列表 ['f', 'o', 'o']。

关于python 列表副本 : is there a difference between old[:] and list(old)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8067765/

相关文章:

python - 如何向 Seaborn Clustermap 添加标题?

python - 类型错误 : QPixmap(): argument 1 has unexpected type 'Figure'

python - 如何使用 scikit-learn 预测具有分类和连续特征的二元结果?

python - 使用参数更改函数中的变量

python - Django文件上传: Upload form has no save method

python - 在 numpy 中动态构造特殊矩阵

python - Ruby 正则表达式中的符号组名称(类似于 Python)

python - 如何在 django 中过滤多对多字段的多个值的模型结果

Python 从 float 组到纹理

python - 如何处理 Pandas 中的 SettingWithCopyWarning