python – 複製列表時,[:]和[::]之間有區別嗎?
我們可以(淺)使用[:]複製列表:
l = [1, 2, 3] z1 = l[:]
我們也可以(淺)使用[::]複製它:
z2 = [::]
現在z1 == z2將為True.在ofollow,noindex" target="_blank">Explain Python’s slice notation 閱讀答案後,我瞭解這些圖片的工作原理.
但是,我的問題是這兩個內部是否有區別?在複製中比其他效率更高,還是做完全相同的事情?
他們之間絕對沒有區別,至少在Python 3中.如果你願意,可以使用dis.dis來檢查每個這些使用的位元組碼:
l = [1, 2, 3, 4]
針對l [:]發出的位元組碼:
from dis import dis dis('l[:]') 10 LOAD_NAME0 (l) 3 LOAD_CONST0 (None) 6 LOAD_CONST0 (None) 9 BUILD_SLICE2 12 BINARY_SUBSCR 13 RETURN_VALUE
而為l [::]傳送的位元組碼:
dis('l[::]') 10 LOAD_NAME0 (l) 3 LOAD_CONST0 (None) 6 LOAD_CONST0 (None) 9 BUILD_SLICE2 12 BINARY_SUBSCR 13 RETURN_VALUE
你可以看到,它們完全一樣.對於構建切片(BUILD_SLICE)的起始和停止值都載入一些無(兩個LOAD_CONSTS),並應用它. NONE是Standard Type hierarchy 中切片文件中所述的預設值:
Special read-only attributes:start
is thelower
bound;stop
is the upper bound;step
is thestep
value; each isNone
if omitted. These attributes can have any type.
使用[:],它的鍵擊少.
實際上有趣的是,在Python 2.x中,生成的位元組程式碼是不同的,由於l [:]的命令較少,可能會稍微更高效:
>>> def foo(): ...l[:] ... >>> dis(foo) 20 LOAD_GLOBAL0 (l) 3 SLICE+0 4 POP_TOP 5 LOAD_CONST0 (None) 8 RETURN_VALUE
而對於l [::]:
>>> def foo2(): ...l[::] ... >>> dis(foo2) 20 LOAD_GLOBAL0 (l) 3 LOAD_CONST0 (None) 6 LOAD_CONST0 (None) 9 LOAD_CONST0 (None) 12 BUILD_SLICE3 15 BINARY_SUBSCR 16 POP_TOP 17 LOAD_CONST0 (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
對於別人也是如此.
http://stackoverflow.com/questions/41648821/is-there-a-difference-between-and-when-copying-a-list