Python:列表和它们的副本 [英] Python: lists and copy of them
问题描述
我无法解释以下行为:
l1 = [1, 2, 3, 4]
l1[:][0] = 888
print(l1) # [1, 2, 3, 4]
l1[:] = [9, 8, 7, 6]
print(l1) # [9, 8, 7, 6]
似乎l1[:][0]
是指副本,而l1[:]
是指对象本身.
It seems to be that l1[:][0]
refers to a copy, whereas l1[:]
refers to the object itself.
推荐答案
l1[:][0] = 888
首先获取l1
(l1[:]
)中所有元素的一部分,(根据列表语义)返回一个新的列表对象包含l1
中的所有对象-它是l1
的浅表副本.
l1[:][0] = 888
first takes a slice of all the elements in l1
(l1[:]
), which (as per list semantics) returns a new list object containing all the objects in l1
-- it's a shallow copy of l1
.
然后用整数888
([0] = 888
)替换该复制列表的第一个元素.
It then replaces the first element of that copied list with the integer 888
([0] = 888
).
然后,复制的列表将被丢弃,因为它没有执行任何操作.
Then, the copied list is discarded because nothing is done with it.
第二个示例l1[:] = [9, 8, 7, 6]
将l1
中的所有元素替换为列表[9, 8, 7, 6]
中的元素.这是切片任务.
Your second example l1[:] = [9, 8, 7, 6]
replaces all the elements in l1
with those in the list [9, 8, 7, 6]
. It's a slice assignment.
这篇关于Python:列表和它们的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!