为什么 Python return 中的逗号为真?

Why does the comma symbol in Python return true?

我想知道为什么逗号“,” returns 正确:

mutant = toolbox.clone(ind1)
ind2, = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
print (ind2 is mutant)
>>>True

但是当我删除逗号符号时:

ind2 = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
print (ind2 is mutant)
>>>False

它 returns 错误。 如果有人能解释这背后的机制,将不胜感激。

当您使用逗号声明或分配变量时,您正在创建一个 tuple

您正在调用 returns 的 deap.tools.mutGaussian() function 一个包含单个值的 元组

Returns: A tuple of one individual.

当您省略逗号时,您会将生成的元组分配给单个变量。

使用逗号,您要求Python将右侧的可迭代对象解包为左侧的一系列名称;因为左侧和右侧都只有一个元素,所以这项工作。您将返回的元组 的值解压缩到单个变量中。

参见Assignment statements reference documenation

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

如果您想在不使用可迭代赋值的情况下测试单个值,则必须手动从元组中获取该值:

ind2 = tools.mutGaussian(mutant, mu=0.0, sigma=0.2, indpb=0.2)
print(ind2[0] is mutant)

注意 [0] 索引。