What does zip do for you?
The ZIP function can be used to iterate and reorganize multiple sets of lists or iterators quickly and easily, which means that the simple two-dimensional array composition work can be done.
Sample code: A two-dimensional array consisting of #-.-coding:utf-8-.-__author__ = ' zt ' L1 = [1, 2, 3, 4]L2 = [5, 6, 7, 8]l3 = [9, ten, one, 12]print zip (L1, L2, L3) # Python 2print (list (Zip (L1, L2, L3)) # Python 3 output: This is a two-dimensional array [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 1) 2) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Zip usage scenario?
Multiple lists make up two-dimensional arrays
As the above example
Convert two-dimensional arrays back to multiple lists
Sample code: #-.-coding:utf-8-.-__author__ = ' zt ' x = [(1, 5, 9), (2, 6, Ten), (3, 7, one), (4, 8, one)]L1, l2, L3 = Zip (*x) Print L 1print l2print L3 Output results: (1, 2, 3, 4) (5, 6, 7, 8) (9, 10, 11, 12)
Using Zip to generate dictionaries
Sample code: #-.-coding:utf-8-.-__author__ = ' zt ' l1 = ["Name", "Age", "gender", "Native Place", "hobby"]L2 = ["Zhang San", 25, "male", "Hainan", "LOL"]print di CT (Zip (L1, L2)) output: {' hobby ': ' LOL ', ' age ': 25, ' birthplace ': ' Hainan ', ' name ': ' Zhang San ', ' gender ': ' Male '}
Considerations and Conclusions:
1. If you use zip to generate a dictionary, the list object or the iterator object can only be two, because each element of the dictionary has only two objects (one is the key and the other is the value).
2. In the process of re-writing code because of the relatively small number of two-dimensional array processing, zip built-in functions are not much use, if there is a lot of use, and then continue to supplement the use of the scene.
Built-in function zip