简体   繁体   English

Python:清单和副本

[英]Python: lists and copy of them

I can not explain the following behaviour: 我无法解释以下行为:

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]

It seems to be that l1[:][0] refers to a copy, whereas l1[:] refers to the object itself. 似乎l1[:][0]指的是副本,而l1[:]指的是对象本身。

This is caused by python's feature that allows you to assign a list to a slice of another list , ie 这是由python的功能引起的,该功能允许您将列表分配给另一个列表的切片 ,即

l1 = [1,2,3,4]
l1[:2] = [9, 8]
print(l1)

will set l1 's first two values to 9 and 8 respectively. l1的前两个值分别设置为98 Similarly, 同样,

l1[:] = [9, 8, 7, 6]

assigns new values to all elements of l1 . l1所有元素分配新值。


More info about assignments in the docs . 有关文档中作业的更多信息。

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 . l1[:][0] = 888首先获取l1l1[:] )中所有元素的切片,(根据列表语义)返回一个包含l1中所有对象的新列表对象-这是一个浅表副本的l1

It then replaces the first element of that copied list with the integer 888 ( [0] = 888 ). 然后,它使用整数888[0] = 888 )替换该复制列表的第一个元素。

Then, the copied list is discarded because nothing is done with it. 然后,复制的列表将被丢弃,因为它没有执行任何操作。

Your second example l1[:] = [9, 8, 7, 6] replaces all the elements in l1 with those in the list [9, 8, 7, 6] . 您的第二个示例l1[:] = [9, 8, 7, 6] l1所有元素替换为列表[9, 8, 7, 6] l1 l1[:] = [9, 8, 7, 6]的元素。 It's a slice assignment. 这是切片任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM