Assignment magic
Sequence unpacking
赋值有很多种,这里说的是序列解包或递归解包:
x,y,z = 1,2,3#多个赋值操作同时进行
print(x,y,z)
x,y = y,x#交换两个变量的值
print(x,y)
values = 1,2,3
print(values)
x,y,z = values
print(x,y,z)
It can also be used in a dictionary:
dict_example = {
'name':'Jack','hobby':'python'}
key,value = dict_example.popitem()
print(key)
print(value)
Tips:
a,b,*rest = 1,2,3,4
print(a)
print(b)
print(rest)
The position of using * can be placed in the first position, so that it will contain a list, and the assignment statement on the right side can be an iterable object
Ps: Note that when using this method, the number of variables before the equal sign and the elements after the equal sign The quantity should be consistent
Chain assignment
Definition: Shortcut to assign the same value to multiple variables
a = b = 4
print(a)
print(b)
Incremental assignment
Use operators to achieve
x = 2
print(x += 1)
print(x *= 2)
print('python' += 'bitch')#字符串也可以
print('python' *= 2)