


Introduction to map() and zip() operation methods in python
Mar 07, 2017 pm 04:11 PMFor map(), its prototype is: map(function, sequence), which is to perform function operations on each element in the sequence.
For example, the previous a, b, c = map(int, raw_input().split()) means to convert the input a, b, c into integers. Another example:
a = ['1','2','3','4'] print map(list,a) print map(int,a)
The first map converts each element in list a into a list, and the second map converts each element in a is an integer.
For zip(), the prototype is zip(*list), list is a list, and 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]
If you want to get the sum of each column, you need to use zip(*list) to unzip the list first and get a tuple list, in which the i-th element The group contains 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 is about how zip and unzip (actually zip and * are used 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(*zipped)) >>> x3 [1, 2, 3] >>> y3 [4, 5, 6]
For more related articles introducing the operation methods of map() and zip() in python, please pay attention to the PHP Chinese website !

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How does springboot read lists, arrays, map collections and objects in yml files?

How to set expiration time map in Java

What are the ways to implement thread safety for Map in Java?

Best Guide to Compressing HTML Files to ZIP

How to use linux compression zip command

How to configure and use the map module in Nginx server

How to convert objects to Maps in Java - using BeanMap

Detailed explanation of decompression file command (zip) under centos7
