[英]Tuple matching vs. variable assignment in Python
I always thought that tuple matching was the same as variable assignment, so I thought these two pieces of code did the same thing:我一直认为元组匹配和变量赋值是一样的,所以我认为这两段代码做了同样的事情:
a = b
b = a + b
and和
a, b = b, a + b
However, that has not been the case in the following two pieces of code that give me different outputs:但是,在以下两段给我不同输出的代码中,情况并非如此:
def fib(seq_len):
a = 1
b = 1
sequence = []
for i in range(seq_len):
sequence.append(a)
a, b = b, a + b
return sequence
fib(10)
which gives the output:这给出了输出:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
and和
def fib(seq_len):
a = 1
b = 1
sequence = []
for i in range(seq_len):
sequence.append(a)
a = b
b = a + b
return sequence
fib(10)
which gives the following output:这给出了以下输出:
[1, 1, 2, 4, 8, 16, 32, 64, 128, 256]
It seems that in the first definition of fib
, the previous value of a
is being used for a, b = b, a + b
but I don't understand how it remembers that previous value because we have assigned a
to another value ie b
before moving on to b = a + b
看来,在第一定义
fib
,以前值a
被用于a, b = b, a + b
,但我不明白它是如何记住以前的值,因为我们都赋予a
到另一个值,即b
在继续b = a + b
a, b = b, a + b
is equivalent to a, b = b, a + b
等价于
t = b, a + b
a, b = t
not不是
a = b
b = a + b # essentially, b = 2 * b
The right-hand side must be fully evaluated before you perform either assignment.在您执行任一分配之前,必须对右侧进行全面评估。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.