TypeError: 'int' object is not subscriptable Genetic Algorithm with search

TypeError: 'int' object is not subscriptable Genetic Algorithm with search

我有这段代码,我正在尝试使用遗传算法进行本地搜索。我想将此数据用于 运行 到 :

[0 : [3,2,1],
 1 : [4],
 2 : [6,5],
 3 : [7],
 4 : [8],
 5 : [9]]

这个想法是等于这个图(但用数字而不是字母):

这是我的代码:

import random

stringSize = 4
top = 10 * stringSize

def value(s):
  return max(-abs(round(0.3*top) - s), .025 - abs(round(0.8 * top) - s))

def ga(times = 10, popSize = 20, mutation_prob = 0.001):
  #population = [int(random.random() * top) for j in range(popSize)]
  population = [0[3,2,1],
                1[4],
                2[6,5],
                3[7],
                4[8],
                5[9]]
  print(len(population))
  print("---")
  history = []
  for i in range(times):
    fitness = [value(population[j]) for j in range(popSize)]
    fitMax = -float('inf')
    
    for j in range(popSize):
      if fitness[j] > fitMax:
        fitMax = fitness[j]
        jBest = j
    history.append(population[jBest])
    fit_sum = sum(fitness)
    probs = [x/fit_sum for x in fitness]
    cutoff = [sum(probs[:j+1]) for j in range(popSize)]
    children = []

    for j in range(popSize):
      r = random.random()
      for k in range(popSize):
        if r < cutoff[k]:
          break
      par1 = population[k-1]
      par2 = population[int(random.random() * popSize)]
      split = int(random.random() * (stringSize + 1))
      child = str(par1)[:split] + str(par2)[split:]
      if random.random() < mutation_prob:
        where = int(random.random() * stringSize)
        what = str(int(random.random() * 10))
        child = child[0:where] + what + child[where + 1:]
      children.append(int(child))
    population = children
  return population

但是 运行它抛出这个错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-34-73e983c9ab93> in <module>()
----> 1 ga()

<ipython-input-33-a504bbf614a5> in ga(times, popSize, mutation_prob)
      4 def ga(times = 10, popSize = 20, mutation_prob = 0.001):
      5   #population = [int(random.random() * top) for j in range(popSize)]
----> 6   population = [0[3,2,1],
      7                 1[4],
      8                 2[6,5],

TypeError: 'int' object is not subscriptable

我该怎么做才能执行它?我做对了吗?

您的数组存在语义错误。例如。 1[2] 无效 python。如果你想做的是将一个数字映射到一个数字数组,请使用一个字典来索引每个列表或一个具有值和子属性的字典数组。

正如其他人已经指出的那样,您可以使用这样的字典:

population = {
   0: [1,2],
   1: [3,4,5],
   ...
}

您遇到的错误通常意味着您正在尝试索引一个无法索引的对象。

只需使用字典:

 population = {0:[3,2,1],
                1:[4],
                2:[6,5],
                3:[7],
                4:[8],
                5:[9]}