【问题标题】:How to Make Python List Mutable as Its Slice is being changed [duplicate]如何使 Python 列表在其切片被更改时可变[重复]
【发布时间】:2015-05-15 16:51:18
【问题描述】:

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]

【问题讨论】:

  • 你不能使用常规的 Python 列表来做到这一点。您可以改为分别传递列表和索引(例如,modify(list, 3, 6))并让 modify 使用它们来修改列表。
  • @thefourtheye:这没有意义,因为他的目标是改变对象。
  • 只需使用切片分配:li=[1,2,3,1,2,3] 然后li[3:6]=[4,5,6]

标签: python list mutable


【解决方案1】:

如果可以选择使用 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 总是返回一个view,它是一个不拥有其数据的数组,而是引用另一个数组的数据

根据您的用例,如果您使用的是 python3,memeoryviewarray.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]

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 2021-03-07
    • 2020-03-10
    • 1970-01-01
    • 2013-10-24
    • 2015-03-08
    • 2019-10-25
    • 1970-01-01
    • 2020-02-05
    相关资源
    最近更新 更多