import random
chosen=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]]
def mutation(chosen, mp):
for i in range(len(chosen)):
if random.random() < mp:
chosen[0][i] = type(chosen[0][i])(not chosen[0][i])
return (chosen)
mp=0.9 #probability
mutated=mutation(chosen, mp)
print (mutated)
假设chosen
代表一个群体中所选择的个体,我试图根据给定的概率对二进制向量(在随机位置)进行变异。并返回一个不同的列表(我仍然不确定是否需要额外的列表)。你知道吗
它并没有像预期的那样工作,有人知道代码中可能有什么错误吗?你知道吗
File "<ipython-input-229-91852a46fa82>", line 9, in mutation
chosen[0][i] = type(chosen[0][i])(not chosen[0][i])
TypeError: 'bool' object is not iterable
另外,如果有人知道一个更方便的方法,这将是完全欢迎。你知道吗
谢谢你!你知道吗
我还在猜测你想要什么,但如果你只想翻转一个二进制位:
输出(注意行中最后一位更改和第三位更改):
相关问题 更多 >
编程相关推荐