Home  >  Article  >  Backend Development  >  Introduction to map() and zip() operation methods in python

Introduction to map() and zip() operation methods in python

高洛峰
高洛峰Original
2017-03-07 16:11:031684browse

For 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 !


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn