This article describes how to use the zip function in Python. the zip function in Python is not used to compress files, but to pass in parameters to return a tuple list, if you need a tuple list, you can refer to the zip function below to accept any number of (including 0 and 1) sequences as parameters. The specific meaning is not easy to express in words. let's look at the example:
1. Example 1:
The code is as follows:
X = [1, 2, 3]
Y = [4, 5, 6]
Z = [7, 8, 9]
Xyz = zip (x, y, z)
Print xyz
The running result is:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
The result shows the basic operation mode of the zip function.
2. Example 2:
The code is as follows:
X = [1, 2, 3]
Y = [4, 5, 6, 7]
Xy = zip (x, y)
Print xy
The running result is:
The code is as follows:
[(1, 4), (2, 5), (3, 6)]
The result shows the processing method of the zip function length.
3. Example 3:
The code is as follows:
X = [1, 2, 3]
X = zip (x)
Print x
The running result is:
The code is as follows:
[(1,), (2,), (3,)]
From this result, we can see that the zip function is run with only one parameter.
4. Example 4:
The code is as follows:
X = zip ()
Print x
The running result is:
The code is as follows:
[]
From this result, we can see how the zip function works without parameters.
5. Example 5:
The code is 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 running result is:
The code is as follows:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
It is generally considered that this is an unzip process, and its operating mechanism is as follows:
Before running zip (* xyz), the xyz value is: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Then, zip (* xyz) is equivalent to zip (1, 4, 7), (2, 5, 8), (3, 6, 9 ))
Therefore, the running result is: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Note: In function calls, the * list/tuple method is used to separate list/tuple and pass it as a location parameter to the corresponding function (provided that the corresponding function supports the location parameter with an indefinite number)
6. example 6:
The code is as follows:
X = [1, 2, 3]
R = zip (* [x] * 3)
Print r
The running result is:
The code is as follows:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
Its operating mechanism is as follows:
[X] generates a list with only one element x
[X] * 3 generates a list with three elements: [x, x, x]
The meaning of zip (* [x] * 3) is clear. zip (x, x, x)