Smooth python and cookbook learning notes (2), pythoncookbook
1. Value assignment of the packet splitting and decompression sequence of tuples
Any sequence (or iteratable object) can be decompressed and assigned to multiple variables through a simple assignment statement. The only premise is that the number of variables must be the same as the number of sequential elements.
1. Parallel assignment:
>>> X = (1, 2) >>> a, B = x # tuples >>> a1 >>> b2
2. Use the * operator to split an iteratable object as a function parameter:
>>> Divmod (20, 8) #20 calculate the remainder of 8, 2*8 + 4 = 20 (2, 4) >>> t = (20, 8) >>> divmod (* t) (2, 4) >>> quotient, remainder = divmod (* t) >>>> quotient, remainder # quotient and remainder (2, 4)
3. Use * args in the function to obtain uncertain number of parameters:
>>> a, b, *rest = range(5)>>> a, b, rest (0, 1, [2, 3, 4]) >>> a, b, *rest = range(3)>>> a, b, rest(0, 1, [2]) >>> a, b, *rest = range(2) >>> a, b, rest(0, 1, [])
4. In parallel assignment, * the prefix can only be used before a variable name, but this variable can appear in any position of the assignment expression:
>>> a, *body, c, d = range(5) >>> a, body, c, d (0, [1, 2], 3, 4) >>> *head, b, c, d = range(5) >>> head, b, c, d ([0, 1], 2, 3, 4)
.