首页 > 解决方案 > 我的程序运行良好,但我不明白为什么?与函数和嵌套列表有关

问题描述

我试图用python制作一个程序来替换任意嵌套列表中的一个项目。要访问该项目,程序将使用索引列表,例如[3, 0, 1]. 这将类似于访问嵌套列表(如list[3][0][1].

我有一个应该替换嵌套列表中的项目的函数。

def ReplaceItemInNestedList(nestedList, indexList, replacement):
    for i in indexList[:-1]:
        nestedList = nestedList[i]
    lastIndex = indexList[-1]
    nestedList[lastIndex] = replacement

像这样使用时它完美地工作。唯一的问题是我不明白为什么会这样:

myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
ReplaceItemInNestedList(myNestedList, myIndexList, replacement)

myNestedList: [[0, 1], [6, 3]]

我不明白如何myNestedList仍然是嵌套列表而不是常规列表。我希望更具体地说,它是一个物品将被替换的地方。那是因为 nestedList 在 for 循环运行时会反复重新定义,并从嵌套列表重新定义到其中的常规列表。

当我将函数放入我的代码中时,我得到了我理解的行为,但这不是我想要的。

myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
for i in myIndexList[:-1]:
    myNestedList = myNestedList[i]
lastIndex = myIndexList[-1]
myNestedList[lastIndex] = replacement

myNestedList: [6, 3]

理想情况下,我希望有class NestedList一个self.value = [[0, 1], [2, 3]]参数在调用 method 时会发生变化changeValueAtIndexList(indexList, replacement),但我真的似乎无法将当前的“神奇”解决方案放入一个类中。请帮助我了解我的程序发生了什么。

标签: pythonfunctionnested-lists

解决方案


我猜你的班级解决方案可能是这样的:

class NestedList:
    def __init__(self, nestedlist):
        self.value = nestedlist
        
    def changeValueAtIndexList(self, indexList, replacement):
        nestedList = self.value
        for i in indexList[:-1]:
            nestedList = nestedList[i]
        lastIndex = indexList[-1]
        nestedList[lastIndex] = replacement
    
#myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6

myNestedList = NestedList([[0, 1], [2, 3]])
myNestedList.changeValueAtIndexList(myIndexList, replacement)
myNestedList.value

# [[0, 1], [6, 3]]

“魔术”是函数或方法内的 nestedList 遍历列表,但方法中的 self.value 或第一个示例中函数外的 myNestedList 仍然指向原始列表。


推荐阅读