为什么Python中的逗号符号返回true?

2024-04-27 05:59:58 发布

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

我想知道逗号符号“,”为什么返回true:

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

但当我去掉逗号符号时:

^{pr2}$

返回false。 如果有人能解释这背后的机制,那将是非常感谢的。在


Tags: truecloneis符号toolboxtoolssigmaprint
2条回答

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

您正在调用的^{} function返回一个包含单个值的元组

Returns: A tuple of one individual.

如果不使用逗号,则将生成的元组分配给单个变量。在

使用逗号,可以要求Python将右侧的iterable解压为左侧的一系列名称;因为左侧和右侧都只有一个元素,所以这样做是可行的。您将返回的元组中的值解压到单个变量中。在

请参见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.

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

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

注意[0]索引。在

相关问题 更多 >