The zip function in Python USES examples
- 2020-04-02 14:31:00
- OfStack
The zip function takes any number of sequences, including 0 and 1, as arguments and returns a list of tuples. The specific meaning is difficult to express in words, see the example directly:
Example 1:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
The result of the operation is:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
From this result you can see the basic operation of the zip function.
2. Example 2:
x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
print xy
The result of the operation is:
[(1, 4), (2, 5), (3, 6)]
From this result you can see how the length of the zip function is handled.
3. Example 3:
x = [1, 2, 3]
x = zip(x)
print x
The result of the operation is:
[(1,), (2,), (3,)]
This result shows how the zip function works with only one argument.
4. Example 4:
x = zip()
print x
The result of the operation is:
[]
This result shows how the zip function works without arguments.
5. Example 5:
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
u = zip(*xyz)
print u
The result of the operation is:
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
This is generally considered to be an unzip process, and it works like this:
Before running zip (* xyz), xyz values are: [(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))
So, the result is: [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Note: *list/tuple is used in the function call to separate the list/tuple and pass it to the corresponding function as a position parameter (provided that the corresponding function supports an indefinite number of position parameters).
6. Example 6:
x = [1, 2, 3]
r = zip(* [x] * 3)
print r
The result of the operation is:
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
It works like this:
[x] generates a list of lists that have only one element, x
[x] * 3 generates a list of lists with 3 elements, [x, x, x]
Zip (* [x] * 3) means zip(x, x, x)