简体   繁体   中英

My program works well but I don't understand why? Something to do with functions and nested lists

I have tried to make a program in python that replaces an item in an arbitrarily nested list. To get to the item, the program would use a list of indexes like [3, 0, 1] . It would be similar to traditional way of accessing nested lists like list[3][0][1] .

I have a function that is supposed to replace an item in a nested list.

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

And it perfectly works when used like that. Only problem is that I don't understand why that is:

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

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

I don't understand how is myNestedList still a nested list instead of a regular one. I'd expect more specifically it to be the one where an item will get replaced. That'd be because nestedList would repeatedly get redefined while the for-loop is running and get redefined from a nested list to the regular list inside it.

When I put the function inside my code I get the behaviour I understand but it's not what I want.

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]

Ideally I'd like there to be a class NestedList with a self.value = [[0, 1], [2, 3]] parameter which would change when called method changeValueAtIndexList(indexList, replacement) , but I really can't seem to be able to put the current "magical" solution into a class. Please help me understand what is going on with my program.

I guess your class solution might be something like this:

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]]

The "magic" is that nestedList inside the function or method traverses the list, but self.value in the method, or myNestedList outside the function in your first example still points at the original list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM