类构造函数 - 类型错误:'int'对象不可下标



这个代码片段是一个更大的遗传算法的一部分。当我运行它时,我得到线路agent.buy = agent.buy[i] + random.randint(0, in_prices_length)TypeError: 'int' object is not subscriptable

我知道你不能对纯整数值进行索引,但我很困惑,因为Agent类中的self.buy被初始化为列表。我不怎么使用面向对象的python,所以我确信我在掩盖一些简单的东西,我就是找不到它

class Agent:
def __init__(self, length):
self.buy = [random.randint(0,length), random.randint(0,length)]
self.fitness = -1
in_prices = None
in_prices_length = None
population = 20
generations = 100
def ga():
agents = init_agents(population, in_prices_length)
for generation in range(generations):
print ('Generation: ' + str(generation))
agents = fitness(agents)
agents = selection(agents)
agents = crossover(agents)
agents = mutate(agents)
def init_agents(population, length):
return [Agent(length) for _ in range(population)]
def mutate(agents):
for agent in agents:
for i in range(2):
if random.uniform(0.0, 1.0) <= 0.1:
agent.buy = agent.buy[i] + random.randint(0, in_prices_length)
return agents
if __name__ == '__main__':

raw = pd.read_csv('IBM.csv')
in_prices = raw['close'].tolist()
in_prices = list(reversed(in_prices))[0:300]
in_prices_length = len(in_prices)
ga()

在方法mutate()中,agent.buy被定义为两个整数的和。

此外,它将取决于csv文件中分配的源数据到值"raw"。

但根据您的代码,它不是一个列表始终。在范围(0..1(中进行迭代,并在第一次迭代中将agent.buy值重置为整数。在第二次迭代中,您再次尝试将buy作为列表访问,但在上一次迭代中将其设置为整数。

我怀疑你想做:

agent.buy[i] = agent.buy[i] + random.randint(0, in_prices_length)

但如果不知道算法,我就不确定:(。

最新更新