【问题标题】:What does this return statement mean? Python这个返回语句是什么意思? Python
【发布时间】:2018-01-31 08:44:24
【问题描述】:

我正在研究一种遗传算法,我找到了一个有效的代码,现在我试图理解,但我看到了这个返回语句:

return sum(1 for expected, actual in zip(target, guess)
  if expected == actual)

它有什么作用?

这里是完整的代码:

main.py:

from population import *

while True:
    child = mutate(bestParent)
    childFitness = get_fitness(child)
    if bestFitness >= childFitness:
        continue
    print(child)
    if childFitness >= len(bestParent):
        break
    bestFitness = childFitness
    bestParent = child

人口.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):
    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)

这是有效遗传算法的完整代码。我修改了一些部分,使其更具可读性。

return 语句在 population.py 文件中的 get_fitness 函数中。

【问题讨论】:

标签: python python-3.x return


【解决方案1】:

发生了几件事:

return sum(...)

这意味着您正在返回一个数字。

sum 的内部是一个generator expression,它创建并运行一个隐式循环。

在这种情况下,1 for expected, actual in zip(target, guess) if expected == actual 创建一系列1 值,每次保护条件为真时创建一个条目 (expected == actual)。

所以这一行有效地创建了如下代码:sum(1, 1, 1, 1, ...)

在生成器表达式中,您有一个zip 调用。 zip 表达式将采用两个(或更多!)序列,并将它们转换为具有两个(或更多!)值的元组的单个序列。也就是说,zip(['a', 'b', 'c'], [1, 2, 3]) 将产生一个类似[('a', 1), ('b', 2), ('c', 3)] 的序列作为其输出。

因此,如果您的expected[1, 2, 3],而您的actual[1, 1, 3],您将得到如下压缩结果:

expected = [1, 2, 3]
actual = [1, 1, 3]
zip(expected, actual)   # [(1, 1), (2, 1), (3, 3)]

生成器表达式包含一个 for,它使用曾经称为“元组解包”的方法从单个聚合(元组)值中分配其 target_list 中的多个目标。

因此,当 zip 表达式生成 (1, 1) 时,for expected, actual 会将其解压缩为 expected=1, actual=1

因此,zip 采用两个等长序列并将它们对应的元素配对:a[0] 与 b[0]、a[1] 与 b[1] 等。for 生成器表达式分配将这些元素放入名为expectedactual 的变量中。 for...if 生成器条件部分比较expected == actual 值,要么生成一个值,要么不生成一个值。因此,结果序列的长度保证小于或等于输入序列的长度,但你不知道它会有多长。生成器的表达式部分就是1。所以你有一个可变长度的 1 序列。 不是 1 或 0。它是 1 或不输入。把所有的 1 加起来就是结果。

【讨论】:

    【解决方案2】:

    它是List Comprehension 的一种类型,它利用了zip() 函数。

    基本上,代码是这样说的:

    • 创建一个列表。
    • 从 zip(目标,猜测)中检索变量“预期”和“实际”。如果它们相等,则将 1 添加到列表中。
    • 重复 zip 中的下一个值(目标,猜测)。
    • 将所有的 1 相加。
    • 返回此总和。

    【讨论】:

      【解决方案3】:

      让我们分解一下:

      return sum(1 for expected, actual in zip(target, guess)
        if expected == actual)
      

      可以写成:

      total = 0
      for i in range(len(target)):
          if target[i] == guess[i]:
              total = total + 1
      return total
      

      zip(a, b) 列出来自ab 的项目对,例如:

      zip([1, 2, 3], ['a', 'b', 'c'])
      

      产生[(1, 'a'), (2, 'b'), (3, 'c')]。所以zip(target, guess) 表达式返回一个列表,其中包含来自target 的第一项和guess 的第一项,然后来自target 的第二项和来自guess 的第二项,依此类推。

      for expected, actual in zip()解包来自zip() 输出的值对,因此这对中的第一个(来自target)进入变量expected,并且这对中的第二个(来自guess)转到变量actual

      1 ... if expected == actual 位表示“如果expected 中的值等于actual 中的值,则为zip() 中的每个项目发出值1。

      sum() 将来自 for 循环的 1 值的数量相加。

      哒哒!现在您有了预期值和实际值相同的项目数。以这种方式编写它有几个原因:

      1. 非常简洁但富有表现力。写了很多 Python 的人一看就懂。
      2. 它可能非常快,因为 Python 解释器正在处理循环、条件等,对 Python 解释器的改进可以使代码更快,而无需了解整个程序。基本上,您是在告诉 Python“我想要完成这件事”,而不是“这里有 100 个小步骤来完成这件事”。

      【讨论】:

      • 非常感谢您。我现在明白了。这正是我所需要的。再次感谢您
      • 我很乐意提供帮助!
      【解决方案4】:

      我认为它返回实际 = 预期的匹配总数。本质上我认为它是检查算法模型能够正确预测的次数

      【讨论】:

      • 是的,它返回的是什么,但所有这些是什么?我不懂语法。
      • 你不明白语法在做什么??只是想了解你想了解的内容
      猜你喜欢
      • 2014-10-31
      • 2012-01-05
      • 2021-12-25
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多