在Python中破坏赋值顺序

2024-04-19 05:33:11 发布

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

今天我遇到了这样一个短语:

(x,_),(y,_) = load_data()

…我想知道任务的先后顺序。在


例如,x,x,x = 1,2,3从我的测试中将x设置为3,它是否真的将x设置为1,2,而不是3?在

它遵循什么规则?在更复杂的情况下会发生什么,比如第一个代码片段?在


Tags: 代码data规则情况load中将
3条回答

这是一个非常有趣的问题,尽管我首先要说的是,您不应该在每行中为同一个变量赋值超过一次。在

第一个示例期望load_data()返回两个元组。它将把(x, _)分配给第一个。下划线是用于解压缩不关心的值的约定。当第二个元组被解包时,它将被覆盖。在

它将把load2()返回的元组加载到您定义的变量x、y和uu中。这又将把每个元组的第一个成员赋给x和y,最后一个值赋给_变量(在第二次调用时被重写)。在

示例:

def load_data():
    return (1,2), (3,4)

(x, _), (y, _) = load_data()

print(x, y, _)

输出

1 3 4

documentation on assignment statements的相关部分是:

If the target list is a comma-separated list of targets, or a single target in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

(强调我的意思:顺序就是这样确定的。)

相关问题 更多 >