逗号分隔的变量赋值 [英] Comma separated variable assignment

查看:75
本文介绍了逗号分隔的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释第 4 行在做什么吗?

Can someone please explain to me what line 4 is doing?

1 def fib2(n):  # return Fibonacci series up to n
2 ...     """Return a list containing the Fibonacci series up to n."""
3...     result = []
4...     a, b = 0, 1  #this line
5...     while a < n:
6...         result.append(a)
7...         a, b = b, a+b
8...     return result    

推荐答案

你描述的是 元组赋值:

What you describe is tuple assignment:

a, b = 0, 1

等价于a = 0b = 1.

然而,如果您想要交换值,它会产生有趣的效果.喜欢:

It can however have interesting effects if you for instance want to swap values. Like:

a,b = b,a

将首先构造一个元组(b,a),然后解开元组并将其分配给ab.因此这不等同于:

will first construct a tuple (b,a) and then untuple it and assign it to a and b. This is thus not equivalent to:

#not equal to
a = b
b = a

但是(使用临时):

t = a
a = b
b = t

通常,如果赋值运算符左侧有一个逗号分隔的变量列表和一个生成元组的表达式,则元组会被解包并存储在值中.所以:

In general if you have a comma-separated list of variables left of the assignment operator and an expression that generates a tuple, the tuple is unpacked and stored in the values. So:

t = (1,'a',None)
a,b,c = t

1 分配给 a,将 'a' 分配给 bNone> 到 c.请注意,这不是语法糖:编译器不会查看左侧变量的数量是否与右侧元组的长度相同,因此您可以从函数等返回元组并将它们解包到单独的变量中.

will assign 1 to a, 'a' to b and None to c. Note that this is not syntactical sugar: the compiler does not look whether the number of variables on the left is the same as the length of the tuple on the right, so you can return tuples from functions, etc. and unpack them in separate variables.

这篇关于逗号分隔的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆