The ZIP function accepts any number of sequences (including 0 and 1) as arguments, returning a tuple list. The specific meaning is not easy to express in words, look directly at the example:
1. Example 1:
Copy Code code as follows:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
XYZ = Zip (x, y, z)
Print xyz
The results of the operation are:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
From this result we can see the basic operation mode of the ZIP function.
2. Example 2:
Copy Code code as follows:
x = [1, 2, 3]
y = [4, 5, 6, 7]
XY = Zip (x, y)
Print XY
The results of the operation are:
Copy Code code as follows:
From this result we can see the length processing of the zip function.
3. Example 3:
Copy Code code as follows:
x = [1, 2, 3]
x = Zip (x)
Print X
The results of the operation are:
Copy Code code as follows:
From this result you can see how the ZIP function works when there is only one parameter.
4. Example 4:
Copy Code code as follows:
The results of the operation are:
Copy Code code as follows:
From this result you can see how the ZIP function works when there are no parameters.
5. Example 5:
Copy Code code as follows:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
XYZ = Zip (x, y, z)
U = Zip (*xyz)
Print U
The results of the operation are:
Copy Code code as follows:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
This is generally considered a unzip process, and its operating mechanism is this:
Before running Zip (*xyz), the value of XYZ is: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
So, zip (*xyz) is equivalent to zip ((1, 4, 7), (2, 5, 8), (3, 6, 9))
Therefore, the results of the operation are: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Note: The use of *list/tuple in function calls means that the list/tuple is separated and passed as a positional parameter to the corresponding function (provided that the corresponding function supports an indefinite number of positional arguments)
6. Example 6:
Copy Code code as follows:
x = [1, 2, 3]
R = Zip (* [x] * 3)
Print R
The results of the operation are:
Copy Code code as follows:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
Its operating mechanism is this:
[x] generates a list of a list, which has only one element x
[x] * 3 generates a list of 3 elements, [x, X, X]
Zip (* [x] * 3) The meaning is clear, zip (x, x, x)