简体   繁体   中英

Object list permutations are not independent from one another in python

Using Python 2.7.

I have four different custom "Airplane" objects in a list, each with their own unique attributes.

Per my requirements, I need to generate all possible permutations of airplane orderings:

    # airplaneList = list of 4 airplane objects
    airplaneListOrderings = list(itertools.permutations(airplaneList))

Per each permutation, I run the permuted list through my program and change airplane attributes in the process, say:

for permutation in airplaneListOrderings:
    for plane in permutation:
        if plane.fuel = 0:
            plane.state = "landing"
        else:
            plane.state = "waiting"

The problem is, that when I finish with the first permutation and start the second permutation, this second permutation saves the states of the first permutation. That is, in the second permutation, the plane that has 0 fuel is already landing.

Am I permuting object references? If so, I need rearrange the actual objects.

How do I create a list of permutations so that if I change the objects in one permutation, it does not change any other permutation?

You can create copies of objects

airplaneListOrderingsnew =[]
import copy
for objects in airplaneListOrderings:
    airplaneListOrderingsnew.append(map(copy.copy,objects))

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