Python zip ()

Source: Internet
Author: User
Tags truncated

>>> Help (Zip) to built-in function zip in module __builtin__:zip (...)    Zip (seq1 [, SEQ2 [...]]), [(Seq1[0], seq2[0] ...), (...)        Return a list of tuples, where each tuple contains the i-th element from each of the    argument sequences.  The returned list is truncated in length to the length of the    shortest argument sequence.>>> list_1 = [' Name ' , ' age ']>>> list_2 = [' Wang ', 23]>>> zip (list_1, list_2) [(' Name ', ' Wang '), (' Age ', ') ']>>> dic T (Zip (list_1, list_2)) {' Age ': $, ' name ': ' Wang '}

If the two parameters are not the same length, then take the short one.

You can also reverse the operation, see below:

>>> list_3{' age ': + ' name ': ' Wang '}>>> list_1 = [' name ', ' age ']>>> list_2 = [' Wang ', 23]>& gt;> list_3 = Zip (list_1, list_2) >>> list_3[(' name ', ' Wang '), (' Age ', ') ']>>> l1, L2 = Zip (*list_3) &G t;>> list_1 = = List (L1) true>>> type (L1) <type ' tuple ' >>>> list_2 = l2false>>> List_2 = = List (L2) True

 

Naturally, you can also manipulate three or one of the parameters:

>>> Zip (list_1) [(' Name ',), (' Age ',)]>>> zip (list_1, list_2, L1) [(' Name ', ' Wang ', ' name '), (' age ', 23, ' Age ')]

  

Python.org's explanation:

1. This function returns a list of tuples, where the  i -th tuple contains the  i -th element f Rom each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there is multiple arguments which is all of the same length, < Span class= "pre" >zip ()  is similar to map ()  with An initial argument of  none . With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

2. The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n) .

3.zip()In conjunction with the * operator can is used to unzip a list

Python 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.