如果Python切片复制了引用,为什么不能使用它来修改原始列表? [英] If Python slice copy the reference, why can't I use it to modify the original list?

查看:110
本文介绍了如果Python切片复制了引用,为什么不能使用它来修改原始列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道切片列表不会生成该副本的副本列表中的对象;只是将引用复制到它们.

但是如果是这样,那为什么不起作用?

But if that's the case, then why doesn't this work?

l = [1, 2, 3]

# Attempting to modify the element at index 1
l[0:2][-1] = 10

# but the attempt fails. The original list is unchanged
l
> [1, 2, 3]

l[0:2][-1]不能指向原始列表索引1处的元素吗?

Shouldn't l[0:2][-1] point to the element at index 1 of the original list?

推荐答案

您是正确的,切片不会复制列表中的项目.但是,它确实会创建一个新的列表对象.

You are right that slicing doesn't copy the items in the list. However, it does create a new list object.

您的评论表明存在误解:

Your comment suggests a misunderstanding:

# Attempting to modify the element at index 1
l[0:2][-1] = 10

这不是对 element 的修改,而是对 list 的修改.换句话说,它实际上是更改列表,以使索引1现在指向数字10".由于您的切片创建了一个新列表,因此您只需更改该新列表以指向其他对象即可.

This is not a modification of the element, it's a modification of the list. In other words it is really "change the list so that index 1 now points to the number 10". Since your slice created a new list, you are just changing that new list to point at some other object.

在您对oldrinb答案的评论中,您说:

In your comment to oldrinb's answer, you said:

为什么l[0:1]l[0:1][0]不同?他们不应该引用同一个对象,即l的第一项吗?

Why are l[0:1] and l[0:1][0] different? Shouldn't they both refer to the same object, i.e. the first item of l?

除了l[0:1]是列表而l[0:1][0]是单个元素的事实之外,这里仍然存在相同的误解.假设some_list是一个列表,索引为ix的对象为obj.这个:

Aside from the fact that l[0:1] is a list while l[0:1][0] is a single element, there is again the same misunderstanding here. Suppose that some_list is a list and the object at index ix is obj. This:

some_list[ix] = blah

. . .是对some_list的操作.不涉及对象obj.这可能会造成混淆,因为这意味着some_list[ix]的语义根据其所处的哪一侧而略有不同.如果你这样做

. . . is an operation on some_list. The object obj is not involved. This can be confusing because it means some_list[ix] has slightly different semantics depending on which side of the assignment it is on. If you do

blah = some_list[ix] + 2

. . .那么您实际上是在列表内的对象上进行操作(即,它与obj + 2相同).但是,当索引操作位于分配的左侧时,它将不再涉及所包含的对象,而仅涉及列表本身.

. . .then you are indeed operating on the object inside the list (i.e., it is the same as obj + 2). But when the indexing operation is on the left of the assignment, it no longer involves the contained object at all, only the list itself.

当您分配给列表索引时,您是在修改 list ,而不是其中的对象.因此,在您的示例中,l[0]l[0:2][0]相同,但这无关紧要;因为您的索引是分配目标,所以它正在修改列表,而不在乎那里已经有什么对象.

When you assign to a list index you are modifying the list, not the object inside it. So in your example l[0] is the same as l[0:2][0], but that doesn't matter; because your indexing is an assignment target, it's modifying the list and doesn't care what object was in there already.

这篇关于如果Python切片复制了引用,为什么不能使用它来修改原始列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆