如何使 Python 列表在其切片发生变化时可变

How to Make Python List Mutable as Its Slice is being changed

Python 的切片操作创建列表指定部分的副本。如何传递父列表的切片,以便当该切片更改时,父列表的相应部分也随之更改?

def modify(input):
    input[0] = 4
    input[1] = 5
    input[2] = 6


list = [1,2,3,1,2,3]
modify(list[3:6])
print("Woud like to have: [1,2,3,4,5,6]")
print("But I got: "  + str(list))

输出:

想拥有:[1,2,3,4,5,6]
但是我得到了:[1,2,3,1,2,3]

如果可以使用 numpy,您可以使用 numpy 来完成:

import  numpy as np


def modify(input):
    input[0] = 4
    input[1] = 5
    input[2] = 6


arr = np.array([1,2,3,1,2,3])
modify(arr[3:6])
print("Would like to have: [1,2,3,4,5,6]")
print("But I got: "  + str(arr))

Would like to have: [1,2,3,4,5,6]
But I got: [1 2 3 4 5 6]

使用basic indexing always returns a view,这是一个不拥有自己数据的数组,而是引用另一个数组的数据

根据您的用例,如果您使用 python3,也许 memeoryview with an array.array 可能有效。

from array import array

arr = memoryview(array("l", [1, 2, 3, 1, 2, 3]))

print(arr.tolist())

modify(arr[3:6])

print("Woud like to have: [1,2,3,4,5,6]")
print((arr.tolist()))
[1, 2, 3, 1, 2, 3]
Woud like to have: [1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6]