Skip to main content
 首页 » 编程设计

python之使用列表位置中包含的项目进行计算(遗传算法适合度)

2025年05月04日16tuyile006

population = [[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [1], [0]], 
 [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]], 
 [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]], 
 [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [3], [3]]] 
 
def ProbabilityList2(population): 
    fitness = [chromosome[1] for chromosome in population] 
    total_weight=sum(fitness) 
    relative_fitness= [(chromosome[1]+1)/total_weight for chromosome in population] 
    return (relative_fitness) 

我正在尝试返回一个基于比例适应值的列表,逻辑如下:[[chromosome],[fitness],[counter]]。我想要做的就是为列表中的所有项目(个人)生成基于此操作的概率列表,但我收到错误:

TypeError: unsupported operand type(s) for +: 'int' and 'list' 

我在使用字典之前解决了这个问题,但是在程序循环期间我得到了重复的条目并且选择函数崩溃了,因为人口中的个体数量和概率(按位置索引)是不均匀的。关于如何以这种格式计算它有什么想法吗?

请您参考如下方法:

chromosome[1] 是一个列表。您可以使用 chromosome[1][0] 访问它,或者将它存储在列表之外。 `