1.元组拆包
元组拆包也叫可迭代元素拆包
元组拆包的基本用法:
>>> lax_coordinates = (33.9425, -118.408056)
>>> latitude, longitude = lax_coordinates # 元组拆包
>>> latitude
33.9425
>>> longitude
-118.408056
还可以用 * 运算符把一个可迭代对象拆开作为函数的参数:
>>> divmod(20, 8)
(2, 4)
>>> t = (20, 8)
>>> divmod(*t)
(2, 4)
>>> quotient, remainder = divmod(*t)
>>> quotient, remainder
(2, 4)
python内置函数divmod() :把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。
除此之外,在元组拆包中使用 * 也可以帮助我们把注意力集中在元组的部分元素上。
用*来处理剩下的元素在 Python 中,函数用 *args 来获取不确定数量的参数算是一种经典写法了。
于是 Python 3 里,这个概念被扩展到了平行赋值中:
>>> a, b, *rest = range(5)
>>> a, b, rest
(0, 1, [2,