Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python for循环创建一个包含x个条目的字典,但在循环之后,字典的长度为<;x_Python_Python 3.x_Genetic Algorithm - Fatal编程技术网

Python for循环创建一个包含x个条目的字典,但在循环之后,字典的长度为<;x

Python for循环创建一个包含x个条目的字典,但在循环之后,字典的长度为<;x,python,python-3.x,genetic-algorithm,Python,Python 3.x,Genetic Algorithm,因此,我正在Python中实现TSP的遗传算法。为了计算下一代,我实现了以下功能: def nextGen(currPop, distDict, numChrome, mutRate): genFit = {} for i in currPop: tmp = fitness(i, distDict) genFit[tuple(i)] = tmp print(tmp) genFitCum = dictCum(

因此,我正在Python中实现TSP的遗传算法。为了计算下一代,我实现了以下功能:

def nextGen(currPop, distDict, numChrome, mutRate):

     genFit = {}

     for i in currPop:
         tmp = fitness(i, distDict)
         genFit[tuple(i)] = tmp
         print(tmp)

     genFitCum = dictCum(genFit)

     print(len(genFit), len(currPop))

     parentSelection = parents(genFitCum, numChrome)

     children = breedPopulation(parentSelection, numChrome)

     nextGeneration = mutatePop(children, mutRate)

     return nextGeneration
distDict
是描述不同城市之间距离的字典。
numChrome
是染色体的数目。
mutRate
是突变率

现在,在第一代之后,我得到了越界的错误,这个错误不应该存在,因为它都在循环中

问题是currPop的长度是恒定的(numChrome),但genFit的长度会减少。这是在循环运行numChrome次之后


我想我的实现可能是在囤积磁盘空间。我尝试使用
del
,但没有成功。

在为密钥赋值之前,请检查您的密钥是否已经存在

# Not sure if str(tuple(i)) will work - regardless apply logic like this to make the Key unique
counter = 0
while((str(tuple(i)) + '_' + str(counter)) in genFit.keys()):
  counter += 1
genFit[str(tuple(i) + '_' + str(counter)] = tmp

在为密钥赋值之前,请检查密钥是否已存在

# Not sure if str(tuple(i)) will work - regardless apply logic like this to make the Key unique
counter = 0
while((str(tuple(i)) + '_' + str(counter)) in genFit.keys()):
  counter += 1
genFit[str(tuple(i) + '_' + str(counter)] = tmp

你需要提供一个新的解决方案。无论如何,我怀疑你的钥匙不是唯一的。
currentPop
中有什么内容?如果词典长度currentPop中有什么内容?如果词典长度