完整代码来自DEAP包示例:
https://github.com/DEAP/deap/blob/0ef6c40b4ba24dbbf1591bd97b08857a1fe3376a/examples/ga/onemax.pyHere
我做了一个测试,人口和个体的大小都是5,我输入了下面的语句:
>>>MAX=max(pop,key=attrgetter("fitness"))
>>>[1,1,1,1,1]
我知道这件事流行健身但是,为什么我不能直接称之为:
>>>pop.fitness
出现错误:
Traceback (most recent call last):
File "<ipython-input-74-b9dde7c090eb>", line 1, in <module>
pop.fitness
AttributeError: 'list' object has no attribute 'fitness'
为什么这个pop.fitness
不能被调用?你知道吗
pop
是list
/iterable。列表本身没有属性fitness
。该列表包含每个对象都有一个属性fitness
。attrgetter('fitness')
创建一个函数,当用对象调用时,该函数返回该对象的fitness
属性。max
使用这个函数从列表中获取它应该排序的值。你知道吗我不知道你的单子上到底有什么,但它是这样的:
这两个是等价的:
max(pop, key=attrgetter('fitness'))
是按照以下思路做的:相关问题 更多 >
编程相关推荐