简体   繁体   English

迭代拆包评估单

[英]Iterable Unpacking Evaluation Order

I recently answered a question where a user was having trouble because they were appending a multi-dimensional array to another array, and it was brought to my attention in my answer that it is possible to use iterable unpacking to populate an x and y value and assign to board[x][y] on the same line. 我最近回答一个用户因将多维数组附加到另​​一个数组而遇到麻烦的问题 ,在我的回答中引起了我的注意,可以使用迭代拆包来填充xy值,并且在同一行上分配给board[x][y]

I had expected this to throw an error as x and y had at the time not been defined, as, even in the iterable-unpacking tag it reads: 我曾预计这会引发错误,因为xy当时尚未定义,即使在读取的iterable-unpacking标签中也是如此:

elements of an iterable are simultaneously assigned to multiple values 可迭代的元素同时分配给多个值

This can be seen as working in the following example: 在以下示例中,这可以看作是有效的:

>>> board = [[0, 0], [0, 0]]
>>> move = [0, 1, 2]
>>> x, y, board[x][y] = move
>>> board
[[0, 2], [0, 0]]

Which is the same as: 与以下内容相同:

>>> board = [[0, 0], [0, 0]]
>>> move = [0, 1, 2]
>>> x = move[0]
>>> y = move[1]
>>> board[x][y] = move[2]
>>> board
[[0, 2], [0, 0]]

And yet when calculating the Fibonacci sequence using: 但是,当使用以下方法计算斐波那契数列时:

a, b = b, a + b

It doesn't evaluate as: 它的评估结果不为:

a = b
b = a + b

And when swapping values with: 并与以下值交换时:

a, b = b, a

It doesn't evaluate as: 它的评估结果不为:

a = b
b = a

So why does this work in the first example? 那么,为什么在第一个示例中这样做呢?

The right side of the = is always evaluated first, in this case it is packing a tuple. 总是首先评估=的右侧,在这种情况下,它正在包装一个元组。 That tuple is then unpacked when interpreting the left hand side. 然后,在解释左侧时会打开该元组的包装。 The left and right sides do not share knowledge of variables. 左侧和右侧不共享变量知识。 The RHS becomes a value and then the LHS uses that value to assign to the variables (labels). RHS成为一个值,然后LHS使用该将其分配给变量(标签)。

In your example the values of x and y are determined after the RHS is evaluated. 在您的示例中,在评估RHS之后确定xy的值。 The unpacking then occurs left to right, so that board[x][y] has valid indices. 然后解压缩从左到右发生,因此board[x][y]具有有效的索引。

Switching the order demonstrates the unpacking sequence: 切换顺序说明了拆箱顺序:

>>> board[x][y], x, y = move[2], move[0], move[1]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-a984ef3168f8> in <module>()
----> 1 board[x][y], x, y = move[2], move[0], move[1]    
NameError: name 'x' is not defined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM