gpt4 book ai didi

Python: TypeError: 'function' 对象没有属性 '__getitem__'

转载 作者:太空宇宙 更新时间:2023-11-04 08:06:36 34 4
gpt4 key购买 nike

我是 python 的新手,我在处理一些代码时遇到了问题。我遇到了错误

TypeError: 'function' object has no attribute '__getitem__' at line 32

我不知道发生了什么。从我在 Internet 上看到的内容来看,这意味着将函数用作列表,但我无法用我的代码弄清楚。我的代码是

#! /usr/local/bin/python


import random


def genFirstGen():
print "First Generation"
generation = []
for chromosomecounter in range(0, 20):
chromosome = []
fitness = 0
for genecounter in range(0, 10):
chromosome.append(random.randrange(0, 2))
for genecounter in range(0, 10):
if (chromosome[genecounter] == 1):
fitness += 1
chromosome.append(fitness)
generation.append(chromosome)
print gene
return generation


def FindMostFit(generation):
failedset = [0,0,0,0,0,0,0,0,0,0,0]
highestfitness = 0
mostfit = 0
fitparents = []
gene = []
for fitcounter in range(0, 10):
for chromosomecounter in range(0, 20):
chromosome = [generation[chromosomecounter]] # The error is here.
fitness = chromosome[10]
highestfitness = 0
if (fitness > highestfitness):
highestfitness = fitness
mostfit = chromosomecounter

fitparents.append(generation[mostfit])
generation[mostfit] = failedset
return fitparents


def BreedMostFit(Parents):
Mother = Parents(random.randrange(0, 10))
Father = Parents(random.randrange(0, 10))
child = []
for genecounter in range(0, 5):
parentgenetaken = random.randrange(0, 2)
if (parentgenetaken == 1):
child.append(Mother[genecounter * 2])
child.append(Mother[(genecounter * 2) + 1])
else:
child.append(Father[genecounter * 2])
child.append(Father[(genecounter * 2) + 1])
return child


def Generation2():
newgeneration = []
for gencounter in range(0, 20):
newgeneration.append(BreedMostFit(FindMostFit(genFirstGen)))
return newgeneration

def GenerationFunction(parentgen):
generation = []
for gencounter in range(0, 20):
generation.append(BreedMostFit(FindMostFit(parentgen)))
return generation

GenerationFunction(Generation2())

我已经无计可施了。谁能帮忙?谢谢!

最佳答案

在第 62 行,您将 genFirstGen 函数传递给 FindMostFit

newgeneration.append(BreedMostFit(FindMostFit(genFirstGen)))

稍后在第 32 行索引它。我猜您想调用该函数并传递其结果。所以将第 62 行替换为

newgeneration.append(BreedMostFit(FindMostFit(genFirstGen())))

关于Python: TypeError: 'function' 对象没有属性 '__getitem__',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30244487/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com