Introduction to map () and zip () operations in python

Source: Internet
Author: User
This article mainly introduces the map () and zip () operations in python. For more information, see map (). its prototype is map (function, sequence ), the function operation is performed on each element of the sequence.

For example, the previous a, B, c = map (int, raw_input (). split () means to convert the input a, B, and c into integers. For example:

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

The first map converts each element in List a to a list, and the second map converts each element in List a to an integer.
For zip (), the prototype is zip (* list), list is a list, and zip (* list) returns a tuple, for example:

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)]

Below are some supplements:

[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, use zip (* list) to unzip the list first to get a list of tuples. the I-th tuples contain the I-th element of each row:

[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 shows how zip and unzip (actually used together with *) 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(*zipped)) >>> x3 [1, 2, 3] >>> y3 [4, 5, 6]


For more information about the map () and zip () operations in python, see The PHP Chinese website!

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.