欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-24 18:08:33
前言 new = old[:] python老鸟都知道以上代码是什么意思。它复制列表old到new。它对于新手来说是种困惑而且应该避免使用这种方法。不幸的是...

前言

new = old[:]

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

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

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

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

z2 = [::]

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

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

最佳答案

他们之间绝对没有区别,至少在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

对于别人也是如此.

总结

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

上一篇:

下一篇: