Append not working like expected [closed]

2019-09-22 10:15发布

问题:

i have the following Problem: For a genetic algorithm i'm creating 5 mutations and store them in a prepared list (see code below).

This is my function where i want to append the mutated drivers:

def startNewRunFromScratch(self):
    self.log.logBlue('Starting new run from scratch', 2, 0)
    parameterSet = []
    parameterSet.append(Parameter('TEST', 0.5, 0, 1))

    defaultGDriver = GDriver(parameterSet)
    gDriverList = []
    gDriverList.append(defaultGDriver)
    m = Mutation(self.mutationRate)
    for i in range(1, self.populationSize, 1):
        g = m.mutate(defaultGDriver)
        self.log.log('After mutaion: '+str(g.parameterSet[0].value), 0, 2)
        gDriverList.append(g)
    self.startSuite(gDriverList)

And here the the startSuite prototype function:

def startSuite(self, gDriverList):
    self.log.logSuccess('Starting suite', 1, 0)
    for g in gDriverList:
        self.log.log('Inside suite: '+str(g.parameterSet[0].value), 0, 2)

The problem is, that the output does not match my logic:

Starting new run from scratch
        After mutaion: 0.5
        After mutaion: 0.5
        After mutaion: 0.5
        After mutaion: 0.740296236666

Starting suite
        Inside suite: 0.740296236666
        Inside suite: 0.740296236666
        Inside suite: 0.740296236666
        Inside suite: 0.740296236666
        Inside suite: 0.740296236666

The expected output:

Inside suite: 0.5
Inside suite: 0.5
Inside suite: 0.5
Inside suite: 0.5
Inside suite: 0.740296236666

Does anyone have an good idea how to solve this problem? Maybee im missing something.

回答1:

You repeatedly append the same Mutation, and end up with multiple references to it in the list. If you want different Mutations, you have to make new ones. (I assume that's what you think is the "problem", as you never explicitly say what is wrong about the output.)