当前位置: 移动技术网 > IT编程>脚本编程>Python > python复制列表时[:]和[::]之间有什么区别

python复制列表时[:]和[::]之间有什么区别

2018年11月09日  | 移动技术网IT编程  | 我要评论

都市之至尊觉醒,雅宝路库房,赵棋荣

前言

new = old[:]

python老鸟都知道以上代码是什么意思。它复制列表old到new。它对于新手来说是种困惑而且应该避免使用这种方法。不幸的是[:]标记法被广泛使用,可能是python程序员不知道更好的列表复制法吧。然而本文给大家介绍的是关于python复制列表时[:]和[::]之间有什么区别,下面来一起看看吧

我们可以(浅)使用[:]复制列表:

l = [1, 2, 3]
z1 = l[:]

我们也可以(浅)使用[::]复制它:

z2 = [::]

现在z1 == z2将为true.在阅读答案后,我了解这些图片的工作原理.

但是,我的问题是这两个内部是否有区别?在复制中比其他效率更高,还是做完全相同的事情?

最佳答案

他们之间绝对没有区别,至少在python 3中.如果你愿意,可以使用dis.dis来检查每个这些使用的字节码:

l = [1, 2, 3, 4]

针对l [:]发出的字节码:

from dis import dis
dis('l[:]')
 1   0 load_name    0 (l)
    3 load_const    0 (none)
    6 load_const    0 (none)
    9 build_slice    2
    12 binary_subscr
    13 return_value

而为l [::]发送的字节码:

dis('l[::]')
 1   0 load_name    0 (l)
    3 load_const    0 (none)
    6 load_const    0 (none)
    9 build_slice    2
    12 binary_subscr
    13 return_value

你可以看到,它们完全一样.对于构建切片(build_slice)的起始和停止值都加载一些无(两个load_consts),并应用它. none是standard type hierarchy中切片文档中所述的默认值:

special read-only attributes: start is the lower bound; stop is the upper bound; step is the step value; each is none if omitted. these attributes can have any type.

使用[:],它的键击少.

实际上有趣的是,在python 2.x中,生成的字节代码是不同的,由于l [:]的命令较少,可能会稍微更高效:

>>> def foo():
...  l[:]
... 
>>> dis(foo)
 2   0 load_global    0 (l)
    3 slice+0    
    4 pop_top    
    5 load_const    0 (none)
    8 return_value 

而对于l [::]:

>>> def foo2():
...  l[::]
... 
>>> dis(foo2)
 2   0 load_global    0 (l)
    3 load_const    0 (none)
    6 load_const    0 (none)
    9 load_const    0 (none)
    12 build_slice    3
    15 binary_subscr  
    16 pop_top    
    17 load_const    0 (none)
    20 return_value 

即使我没有定时这些(我不会,差异应该很小)看起来,由于只需要更少的指示,l [:]可能稍微好一点.

这种相似性当然不存在于列表中;它适用于python中的所有序列:

# note: the bytecode class exists in py > 3.4
>>> from dis import bytecode
>>>
>>> bytecode('(1, 2, 3)[:]').dis() == bytecode('(1, 2, 3)[::]').dis() 
true
>>> bytecode('"string"[:]').dis() == bytecode('"string"[::]').dis() 
true

对于别人也是如此.

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网