Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

python - How to mutate list permanently?

def deep_reverse(L) :
    for i in range (len(L)-1,-1,-1):
        L=L[::-1]
    for i in range (len(L)-1,-1,-1):
        L[i]=L[i][::-1]  

L = [[0, 1, 2], [1, 2, 3], [3, 2, 1], [10, -10, 100]]
deep_reverse(L) 
print(L)

So I have this code here and a function called deep_reverse(L). I am trying to mutate the list L, at the end when i print(L) it prints out L = [[0, 1, 2], [1, 2, 3], [3, 2, 1], [10, -10, 100]]. However, when I print from within the function, I get L= [[2, 1, 0], [3, 2, 1], [1, 2, 3], [100, -10, 10]], which is what I want. How can i permanently mutate L so that it stays that way when I print it outside the function.

question from:https://stackoverflow.com/questions/65928411/how-to-mutate-list-permanently

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're not mutating anything. The function creates a new list and assigns it back to the local variable, which has no effect on the caller's variable.

Also, your first for loop is repeatedly reversing L. If the list has an even number of elements, it will reverse it back to the original order.

Use slice assignment to modify the list in place.

def deep_reverse(L):
    L[:]=L[::-1]
    for i in range (len(L)-1,-1,-1):
        L[i][:]=L[i][::-1] 

Note also that your code only reverses two levels deep. Use recursion to handle any depth.

def deep_reverse(L):
    if isinstance(L, list):
        L[:] = L[::-1]
        for subL in L:
            deep_reverse(subL)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...