1. 序列解包
# 同時給多個變量賦值
x, y, z = 1, 2, 3
print(x, y, z)
# 交換變量的值
x, y = y, x
print(x, y, z)
# 返回元組
values = 1, 2, 3
print(values)
# 解包到三個變量中
x, y, z = values
print(x, y, z)
# 解包字典到鍵值變量
key, value = {'name': 'zenos', 'age': 22}.popitem()
print(key, value)
# 序列包含的元素個數(shù)必須和等號左邊的相同
# x, y, z = 1, 2
# 使用*星號運算符, 接收來自多余的值
a, b, *rest = [1, 2, 3, 4, 5]
print(a, b, rest)
# 將*放在中間
a, *rest, b = 'Albus Percival Wulfric Brian Dumbledore'.split()
print(a, rest, b)
# 將*放在最前
*rest, a, b = 'Albus Percival Wulfric Brian Dumbledore'.split()
print(rest, a, b)
# 解包其他序列
a, b , *rest = 'abcdef'
print(a, b, rest)
========================1=========================
1 2 3
2 1 3
(1, 2, 3)
1 2 3
age 22
1 2 [3, 4, 5]
Albus ['Percival', 'Wulfric', 'Brian'] Dumbledore
['Albus', 'Percival', 'Wulfric'] Brian Dumbledore
a b ['c', 'd', 'e', 'f']
2. 鏈式賦值
x = y = [1, 2, 3]
print(x is y)
# 等價于
x = [1, 2, 3]
y = x
print(x is y)
# 不等價
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y)
========================2=========================
True
True
False
3. 增強賦值
x = 2
x += 1
x *= 2
print(x)
print((2+1)*2)
# 其他序列解包
fnord = 'foo'
fnord += 'bar'
fnord *= 2
print(fnord)
========================3=========================
6
6
foobarfoobar