我一直在尝试生成不同的字典结构(与Python中的不同类实例有关),并用[0,1)之间的随机数填充。字典的键不是那么重要。但是,主要的问题是,当我尝试生成具有随机值的字典时,它们全部以相同的顺序出现:
{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}
{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}
{'p0': 0.8834439890229875, 'p1': 0.4542011548977558, 'd0': 0.041855079212439805, 'c0': 0.30179244567633823, 'c1': 0.026356543619428408, 'c2': 0.24603169392476631}
代码:
''' Individual Class '''
from random import Random
class Individual:
chromosome = {} #The chromosome of an individual is a random generated dictionary.
randomInstance = Random(datetime.now())
def __init__(self, numP, numD, numC):
self.randomInstance.seed()
for i in range(numP):
plant = "p"
plant += str(i)
self.chromosome[plant] = self.randomInstance.random()
for j in range(numD):
plant = "d"
plant += str(j)
self.chromosome[plant] = self.randomInstance.random()
for k in range(numC):
plant = "c"
plant += str(k)
self.chromosome[plant] = self.randomInstance.random()
def main():
list = []
for i in range(4):
inst = Individual(2, 1 ,3)
list.append(inst.chromosome)
print(list)
我正在尝试为每个类实例获取不同的序列。
希望有人可以提供帮助。谢谢大家。
答案 0 :(得分:0)
您要将chromosome
和randomInstance
声明为类属性,以便它们在该类的所有实例之间共享。如果需要每个实例,请在 init 中将它们初始化为类属性。