Description of how map () and zip () operations are done in Python

Source: Internet
Author: User
for map () its prototype is: Map (function,sequence), which is to perform function functions on each element of the sequence sequence.

For example, the previous a,b,c = Map (Int,raw_input (). Split ()), meaning that the input a,b,c is converted to an integer. Another example:

A = [' 1 ', ' 2 ', ' 3 ', ' 4 ']print map (list,a) print map (int,a)

The first map is to convert each element in list A to a list, and the second map converts each element in a to an integer.
For Zip (), the prototype is a ZIP (*list), List is a listing, and the ZIP (*list) returns a tuple, such as:

list = [[1,2,3],[4,5,6],[7,8,9]]t = Zip (*list) print T

Output: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

x = [1,2,3,4,5]y = [6,7,8,9,10]a = Zip (x, y) print a

Output: [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]

Here are some additions:

[python] >>> list = [[0,1,2],[3,1,4]] >>> [sum (x) for x in list] [3, 8] >>> map (sum,list) [3, 8 ]

To get the sum of each column, you need to unzip the list with a zip (*list) to get a list of tuples, where the I tuple contains the I element of each line:

[python] >>> list = [[0,1,2],[3,1,4]] >>> zip (*list) [(0, 3), (1, 1), (2, 4)] >>> [sum (x) for X In Zip (*list)] [3, 2, 6] >>> map (sum,zip (*list)) [3, 2, 6]

The following example is about how the zip and unzip (in fact, zip and * together) work:

[Python] >>> x=[1,2,3] >>> y=[4,5,6] >>> zipped = Zip (x, y) >>> zipped [(1, 4), (2, 5), (3, 6)] >>> x2,y2=zip (*zipped) >>> x2 (1, 2, 3) >>> y2 (4, 5, 6) >>> X3,y3=map (List,zip (*zippe d) >>> X3 [1, 2, 3] >>> Y3 [4, 5, 6]


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.