简体   繁体   English

将字符串元素中的1s翻转为0,反之亦然

[英]Flip 1s to 0s and viceversa in string elements

I'm writing a simple genetic algorithm and the mutation operator requires me to randomly flip a "gene" (ie: a single char in a string) with a certain probability. 我正在编写一个简单的遗传算法,并且变异运算符要求我以一定的概率随机翻转“基因”(即字符串中的单个字符)。

This is an example of the list I need to go through flipping randomly each character: 这是我需要随机翻转每个字符的列表的一个示例:

a = ['0010010', '0011101', '1101101', '0100110', '1010100', '1000111', '1001110', '0010011', '0011111', '0001001', '0101000', '1010010', '1110000', '0000001', '1100111', '1001100', '1000001', '1001010']

I loop through each character in each element of the list to check if I have to flip it like so: 我遍历列表中每个元素中的每个字符以检查是否必须像这样翻转它:

for elem in a:
    for char in elem:
        r = random.random()
        if r<prob:
            # Flip the char.
            f_char = 1-int(char)
            # Replace the new flipped char in the element?

(where prob is a fixed float [0,1] ) (其中prob是固定浮点[0,1]

I'm not sure how I could update the elem with the new flipped character in the case I have to. 我不确定在必须的情况下如何使用新的翻转字符更新elem I'd also need this process to run as fast as possible since my actual list is somewhat large. 我还需要此过程尽可能快地运行,因为我的实际列表有些大。

Two choices: 两种选择:

One, you can use a list of integers instead of a string. 一种,您可以使用整数列表而不是字符串。 Then, mutate them in-place: 然后,将它们原位变异:

a = [[0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 1, 0, 1]]
for elem in a:
    for i, bit in enumerate(elem):
        r = random.random()
        if r < prob:
            elem[i] = 1 - bit

Two, you can still use strings, but then you have to replace the entire string every time you want to change one character in it, because Python strings are immutable. 第二,您仍然可以使用字符串,但是每次您要更改其中一个字符时,都必须替换整个字符串,因为Python字符串是不可变的。 Best way is using a generator comprehension, as in inspectorG4dget's answer: 最好的方法是使用生成器理解,如inspectorG4dget的答案:

a = ['0010010', '0011101']
for i, elem in enumerate(a):
    a[i] = ''.join(str(1 - int(char)) if random.random() < prob else char
                   for char in elem)

Strings are immutable, so you'll have to replace the entire chromosome in your list of chromosomes, when you mutate even one gene in the chromosome. 字符串是不可变的,因此,即使对染色体中的一个基因进行突变,也必须替换染色体列表中的整个染色体。 So try this: 所以试试这个:

for i,elem in enumerate(a):
    a[i] = ''.join(char if random.random()>prob else str(1-int(char)) for char in elem)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM