Python-zip method

Source: Internet
Author: User

zip Returns an iterator that combines multiple, iterative objects into a single tuple sequence.

1. Loop the data for multiple lists:

 1  letters = [ " a  , "  b  , "  c   " ]  2  nums = [1, 2, 3 ]  3  4  for  letter, num in   zip (Letters, nums):  5   Print  ( " {}: {}  . Format (letter, num)) 

2. Combine data from multiple lists into a list of tuple:

1 list (zip (['a', 'b', 'c' ) ], [1, 2, 323#  get: [(' A ', 1], (' B ', 2), (' C ', 3)].

3. Split the list of tuple components into multiple tuple:

1Some_list = [('a', 1), ('b', 2), ('C'-R)]2Letters, Nums = ZIP (*some_list)3 4 #Results5 #Letters: (' A ', ' B ', ' C ')6 #nums: (1, 2, 3)7          

* Note that even if the list is not a tuple, it can still be split and the result of the split is a tuple:

Some_list = (('a', 1), ('b', 2), ('c' , 3= Zip (*some_list)#

* Note that even if a tuple is not a list, it can still be split and the result of the split is a tuple:

Some_list = [['a', 1], ['b', 2], ['c' , 3= Zip (*some_list)

Give me a chestnut:

# transpose data from the 4x3 matrix to the 3x4 matrix. = ( (0, 1, 2), (3, 4, 5), (6, 7, 8), (9,, one= Zip (*data)# Result:   6>[(0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11)]

* Notable is:

When a zip is used to consolidate data, it returns an iterative iterator that can be used for looping, or it can be converted to a list or tuple via the list () , tuple () method.

zip is used to split the data, you can split the list, split the tuple, but always return a list, and each element of the list is a tuple

Python-zip method

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.