lis中二元向量的突变

2024-09-27 07:35:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

另外,如果有人知道一个更方便的方法,这将是完全欢迎。你知道吗

谢谢你!你知道吗


Tags: inimport列表forlenifdeftype
1条回答
网友
1楼 · 发布于 2024-09-27 07:35:05

我还在猜测你想要什么,但如果你只想翻转一个二进制位:

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:
            pos = random.randrange(len(chosen[i][0]))
            chosen[i][0][pos] = 0 if chosen[i][0][pos] else 1

# before
for item in chosen:
    print(item)
print()

mutation(chosen, 1) # 100% of the time, for now

# after
for item in chosen:
    print(item)

输出(注意行中最后一位更改和第三位更改):

[[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]]

[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [3], [0]]
[[0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]]

相关问题 更多 >

    热门问题