"Python Tour" chapter II (eight): Zip zip and map zipper

Source: Internet
Author: User

1.zip Zipper


• Function: Merge two lists into a list of elements as tuples;

• The demo is as follows:

>>> a = range (0,5) >>> B = Range (5,10) >>> a[0, 1, 2, 3, 4]>>> b[5, 6, 7, 8, 9]>>& Gt Zip (A, b) [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]>>> Zip (b,a) [(5, 0), (6, 1), (7, 2), (8, 3), (9, 4)]

• If the number of two list elements is inconsistent, the zip is automatically ignored:

>>> a = range (1,5) >>> B = [' A ', ' B ', ' C ']>>> a[1, 2, 3, 4]>>> b[' A ', ' B ', ' C ']>> > Zip (b) [(1, ' a '), (2, ' B '), (3, ' C ')]


• Using the zip function, you can create a dictionary:

>>> key = [' name ', ' girlfriend ']>>> values = [' xpleaf ', ' CL ']>>> zip (key, values) [(' Name ', ' XP Leaf '), (' Girlfriend ', ' cl ')]>>> dict (Zip (key, values)) {' Girlfriend ': ' CL ', ' name ': ' Xpleaf '}>>> Dict (Zip (key, values))



2.map


The map function is very powerful, here only to mention its similar to the ZIP function;

>>> a = range (1,5) >>> B = [' A ', ' B ', ' C ', ' d ']>>> map (A, B) Traceback (most recent call last): F  Ile "<stdin>", line 1, in <module>typeerror: ' List ' object was not callable>>> map (none,a,b) [(1, ' a '), (2, ' B '), (3, ' C '), (4, ' d ')]

• You can see that the map needs to specify the first parameter, because map does not automatically ignore two different numbers of lists, specifying the parameters as padding for the list of insufficient numbers:

>>> B.pop () ' d ' >>> map (none, a, B) [(1, ' a '), (2, ' B '), (3, ' C '), (4, none)]



This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1695709

"Python Tour" chapter II (eight): Zip zip and map zipper

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.