Lab Environment:
[Email protected] ~]# Python-vpython 2.7.5
1. Sequence Unpacking
Multiple assignment operations can be performed simultaneously
>>> x, y, z = 1,2,3>>> x1>>> print Y,Z2 3
Swapping two or more variables is also possible.
>>> x, y = y,x>>> print x,y,z2 1 3
What is done here is called sequence unpacking or recursive unpacking--the sequence of multiple values is untied and then placed in the sequence of variables. A more vivid representation:
>>> values = 1,2,3>>> values (1, 2, 3) >>> x, y, z = values>>> Print X,Y,Z1 2 3
This feature is more useful when a function or method returns a tuple (or other sequence or iterative object). Suppose you need to get (and delete) any key-value pairs in the dictionary, you can use the Popitem method, which returns a key-value pair as a tuple. Then the tuple can be directly assigned to two variables.
>>> AddressList = {' Wang ': ' 123456 ', ' Ni ': ' 23456 '}>>> key,value = Addresslist.popitem () >>> Key ' Ni ' >>> value ' 23456 '
The sequence unpacking allows the function to return more than one value and to package the Narimoto group, which is then easily accessible through an assignment statement. So the number of elements in the unpacked sequence must be exactly the same as the number of variables placed on the left of the assignment symbol =. Otherwise python throws an exception when the value is assigned.
>>> x, y, z = 1,2traceback (most recent call last): File "<stdin>", line 1, in <module>valueerror: Need more than 2 values to unpack>>> x, y, z = 1,2,3,4traceback (most recent call last): File "<stdin>", Line 1, in <module>valueerror:too many values to unpack
2. Chained assignment
Chained assignment is a shortcut to assigning the same value to multiple variables. A bit like the parallel assignment above, but only one value is processed
>>> x=y=[1,2,3]>>> Print x,y[1, 2, 3] [1, 2, 3]
Equivalent to
y=[1,2,3]
X=y
3. Incremental assignment
The expression operator x=x+1 in the assignment expression (in this case, +) is placed on the left side of the assignment operator =, written as x+=1. This notation is called incremental assignment and is applicable for standard operators such as *,/, and%.
>>> x=2>>> x+=1>>> x3>>> x*=2>>> X6
It is also suitable for other data types. As long as the two-dollar operator itself applies these data types.
>>> fnord= ' foo ' >>> fnord+= ' bar ' >>> fnord ' foobar ' >>> fnord*=2>>> fnord ' Foobarfoobar '
Incremental assignment can make your code more compact and concise.
Reference:
Basic Python Tutorial (Second edition. revision)
Python Assignment magic tricks