如何更改Python切片时,如何使Python列表可变

Sha*_*ing 1 python list mutable

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))
Run Code Online (Sandbox Code Playgroud)

输出:

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

Pad*_*ham 5

如果使用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]
Run Code Online (Sandbox Code Playgroud)

使用基本索引始终返回一个视图,该视图一个不拥有其数据的数组,而是引用另一个数组的数据

根据您的使用情况,如果您使用的是python3,则可能使用array.arraymemeoryview可能会有效.

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]
Run Code Online (Sandbox Code Playgroud)