Built-in function zip

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.