Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Why does my original list change?

I a wrote a function SwapCities that is able to swap entries 3 and 4 in a list.

So f.e. [0,1,2,3,4] should become [0,1,2,4,3]. This function works perfectly, but strangely my original list also changes which I do not want.

This is my code:

def SwapCities(solution):
    n = 3##randint(0,NumberOfCities-1)
    m = 4##randint(0,NumberOfCities-1)
    result = solution
    temp1 = solution[n]
    temp2 = solution[m]
    result[n] = temp2
    result[m] = temp1
    return result

print "Start"
IncumbentSolution = list(x for x in range(0,NumberOfCities))
print IncumbentSolution

print "After swap" NewSolution = SwapCities(IncumbentSolution)
print NewSolution

print "Original solution"
print IncumbentSolution

I get the following result:

How many cities?
8 Start [0, 1, 2, 3, 4, 5, 6, 7]
After swap [0, 1, 2, 4, 3, 5, 6, 7]
Original solution [0, 1, 2, 4, 3, 5, 6, 7]   (why did this change?!)

As you can see my original solution changed which it should not do.

I have no clue why this happens. Even when I change the code such that the changes to are applied to a copy of the original list I get this result. Could someone explain what I am doing wrong?

IncumbentSolution = list(x for x in range(0,NumberOfCities))
print "Start"
print IncumbentSolution

print "After swap"
tmpsolution = IncumbentSolution
NewSolution = SwapCities(tmpsolution)
print NewSolution

print "Original solution"
print IncumbentSolution
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

SwapCities is mutating the contents of solution. Since solution points to the same list as IncumbentSolution, the values inside IncumbentSolution are altered too.


To preserve the original values in IncumbentSolution, make a new copy of the list:

tmpsolution = list(IncumbentSolution)

makes a shallow copy of the the original list. Since the contents of IncumbentSolution are immutable numbers, a shallow copy suffices. If the contents included, say, dicts which were also being mutated, then you would need to make a deep copy of the list:

import copy
tmpsolution = copy.deepcopy(IncumbentSolution)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...