这个任务是什么?蟒蛇

时间:2017-08-23 10:46:12

标签: python python-3.x variable-assignment

我从一本书中复制了遗传密码,我找到了这个任务:

childGenes[index] = alternate \
    if newGene == childGenes[index] \
    else newGene

完整的代码是这样的: main.py:

from population import *

while True:
    child = mutate(bestParent)
    childFitness = get_fitness(child)
    if bestFitness >= childFitness:
        continue
    print(str(child) + "\t" + str(get_fitness(child)))
    if childFitness >= len(bestParent):
        break
    bestFitness = childFitness
    bestParent = child

population.py:

import random

geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.,1234567890-_=+!@#$%^&*():'[]\""
target = input()

def generate_parent(length):
    genes = []
    while len(genes) < length:
        sampleSize = min(length - len(genes), len(geneSet))
        genes.extend(random.sample(geneSet, sampleSize))
    parent = ""
    for i in genes:
        parent += i
    return parent

def get_fitness(guess):
    total = 0
    for i in range(len(target)):
        if target[i] == guess[i]:
            total = total + 1
    return total
    """
    return sum(1 for expected, actual in zip(target, guess)
        if expected == actual)
    """

def mutate(parent):
    index = random.randrange(0, len(parent))
    childGenes = list(parent)
    newGene, alternate = random.sample(geneSet, 2)
    childGenes[index] = alternate \
        if newGene == childGenes[index] \
        else newGene

    child = ""
    for i in childGenes:
        child += i

    return child

def display(guess):
    timeDiff = datetime.datetime.now() - startTime
    fitness = get_fitness(guess)
    print(str(guess) + "\t" + str(fitness) + "\t" + str(timeDiff))

random.seed()
bestParent = generate_parent(len(target))
bestFitness = get_fitness(bestParent)
print(bestParent)

赋值在population.py中,在mutate函数中。我从未见过这种变量赋值。这是什么?什么是&#34; \&#34;符号是什么意思?

4 个答案:

答案 0 :(得分:2)

分配已分为多行。反斜杠joins the lines。作业可以改写为:

childGenes[index] = alternate if newGene == childGenes[index] else newGene

这是conditional expression(有时称为“三元运算符”),相当于:

if newGene == childGenes[index]:
    childGenes[index] = alternate
else:
    childGenes[index] = newGene

答案 1 :(得分:1)

它转换为:

if newGene == childGenes[index]:
   childGenes[index] = alternate
else:
   childGenes[index] = newGene

答案 2 :(得分:0)

这里的反斜杠是一个简单的换行转义字符。所以python解释器将这些行读为一行:

childGenes[index] = alternate if newGene == childGenes[index] else newGene

在这里讨论了一线条件分配:

https://stackoverflow.com/questions/7872838/one-line-if-condition-assignment

答案 3 :(得分:0)

它是:

的替代方案
if newGene == childGenes[index]:
    childGenes[index] = alternate
else:
    childGenes[index] = newGene