跳转至

2.13.简洁的Python

Windows 10
Python 3.6.9 @ MSC v.1915 64 bit (AMD64)
Latest build date 2020.06.23

序列解包

x, y, z = (1, 2, 3)
print(x, y, z)

x, y = y, x
print(x, y)
1 2 3
2 1

要解包的序列包含的元素个数必须与你在等号左边列出的目标个数相同,否则Python将引发异常。

try:
    x, y = (1, 2, 3)
except ValueError as e:
    print(e)

try:
    x, y, z = (1, 2)
except ValueError as e:
    print(e)
too many values to unpack (expected 2)
not enough values to unpack (expected 3, got 2)

可使用星号运算符( * )来收集多余的值,这样无需确保值和变量的个数相同,如下例所示:

x, *y = (1, 2, 3)
print(x, y)

x, *y, z = (1, 2, 3, 4)
print(x, z)
1 [2, 3]
1 4

链式赋值

链式赋值是一种快捷方式,用于将多个变量关联到同一个值。

x = y = 1
print(x, y)
1 1

上述代码与下面的代码等价:

y = 1
x = y

请注意,这两条语句可能与下面的语句不等价:

x = somefunction()
y = somefunction()

if/else三元表达式

a = 2
a if a > 0 else 1
2