简体   繁体   中英

Python Assigning value from one variable to another

I am trying to implement some sort of local search. For this I have two arrays, which represent a list, that I am trying to optimize. So I have one array as the current best array and the one I am currently analyzing.

At the beginning I am shuffling the array and set the current best array to the shuffled array.

random.shuffle(self.matchOrder)
self.bestMatchOrder = self.matchOrder

Then I am swapping a random neighboured pair in the array. Now the problem I have is that when I am swapping the values in self.matchOrder , the values in self.bestMatchOrder get swapped.

a = self.matchOrder[index]
self.matchOrder[index] = self.matchOrder[index + 1]
self.matchOrder[index + 1] = a

"index" is given to the function as a parameter, it is just randomly generated number.

I guess I did something wrong assigning the variables, but I can't figure out what. So what can I do to only assign the value of the array to the other array and not make it apply the same changes to it, too?

When you use self.bestMatchOrder = self.matchOrder Then Python doesn't allocates a new memory location to self.bestMatchOrder instead both are pointing to the same memory location. And knowing the fact that the lists are mutable data type, Hence any changes made in the self.matchOrder would get reflected in the self.bestMatchOrder .

import copy

self.bestMatchOrder = copy.deepcopy(self.matchOrder)

However if you are using linear lists or simple lists the you can also use self.bestMatchOrder = self.matchOrder[:] But if yo are using nested lists then deepcopy() is the correct choice.

If you want to copy a list, you can use slice operation:

list_a = [1, 2, 3]
list_b = list_a[:]
list_a = [0, 0, 42]
print list_a  # returns [0, 0, 42]
print list_b  # returns [1, 2, 3], i.e. copied values

But if you have more complex structures, you should use deepcopy , as @anmol_uppal advised above.

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