gpt4 book ai didi

python - 按索引覆盖列表切片中的值

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:00 24 4
gpt4 key购买 nike

我在更改列表切片的值(按索引)时遇到以下意外行为:

# Expected behavior:
>>> a = [1,2,3,4]
>>> a
[1, 2, 3, 4]
>>> a[2] = 5
>>> a
[1, 2, 5, 4]
>>> a[2:]
[5, 4]
>>> a[2:] = ['y', 2]
>>> a
[1, 2, 'y', 2]
>>> a[1:]
[2, 'y', 2]
>>> a[1:][0]
2
# Unexpected behavior:
>>> a[1:][0] = 'hello'
>>> a
[1, 2, 'y', 2] # I would have expected [1, 'hello', 'y', 2] here

如您所见,您可以通过将列表分配给切片来覆盖原始列表,如 a[2:] = ['y', 2]。但是,如果您尝试通过索引覆盖切片的元素(或通过像 >>> a[1:][:1] = [2] 这样的切片构造),则没有错误,但是原始列表不会更新。

有没有正确的方法来做到这一点?为什么 Python (3.7.3) 会这样?

最佳答案

当您对列表进行切片时,您实际上创建了列表的副本(切片的部分),因此它们不会相互影响:

x = [1, 2, 3, 4]
y = x[1:] # y = [2, 3, 4]

y[0] = "hi" # y = ["hi", 3, 4]
# y is a copy of x, so any changes made to y aren't reflected in x

print(x) # [1, 2, 3, 4]

索引赋值运算符可以使用一个索引(即 x[i] = something)或切片对象(start:stop:step,即 x[1:5] = [1, 2, 3, 4])。但是,您尝试更改切片的元素,结果没有任何更改:

x[1:][0] = "hi"  # x is unchanged
# x[1:] is a copy of x, so changes to it (like setting the first element to "hi")
# does nothing useful

相反,您可以自己计算索引或范围:

# instead of:
x[start:][1] = "hi"
# use:
x[start + 1] = "hi"

关于python - 按索引覆盖列表切片中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622499/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com