Python 在一行中分配多個變量的實際步驟是什么?我過去經(jīng)常做 A[0], A[1] = A[1], A[0] 來交換,但最近我在分配鏈表時遇到了一個錯誤。# insert self->node->...def insert_next(self, node): node.next, node.prev = self.next, self self.next, self.next.prev = node, nodeself.next變得node比我預期的要早,所以分配變成self.next, node.next = node, node 但是,如果我這樣做self.next.prev, self.next = node, node有用!我“假設(shè)”的步驟是1. cache values at the right side2. assign to left side one by one, left to right不是1. cache values at the right side2. cache the ref at the left side2. assign to ref one by one, left to right那么,有哪些步驟呢?
1 回答

倚天杖
TA貢獻1828條經(jīng)驗 獲得超3個贊
Python中有一種叫做“擴展賦值”的東西。
長話短說,您可以通過賦值來擴展迭代。例如,這段代碼計算并展開右側(cè),實際上是一個元組,并將其分配給左側(cè):
a, b = 3, 5
或者
tup = (3, 5)
a, b = tup
這意味著在 Python 中,您可以用一行交換兩個變量:
a, b = b, a
它評估右側(cè),創(chuàng)建一個 tuple (b, a),然后擴展元組并分配給左側(cè)。
有一個特殊規(guī)則,如果任何左側(cè)變量“重疊”,則賦值從左到右。
i = 0
l = [1, 3, 5, 7]
i, l[i] = 2, 0 # l == [1, 3, 0, 7] instead of [0, 3, 5, 7]
所以在你的代碼中,
node.next, node.prev = self.next, self
此分配是并行的,node.next并且node.prev不“重疊”。但是對于下一行:
self.next, self.next.prev = node, node
由于self.next.prev取決于self.next,它們“重疊”,因此self.next首先分配。
添加回答
舉報
0/150
提交
取消