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

高洛峰
Release: 2017-03-07 16:11:03
Original
1683 people have browsed it

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)
Copy after login

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
Copy after login

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
Copy after login

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]
Copy after login

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]
Copy after login

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]
Copy after login


For more related articles introducing the operation methods of map() and zip() in python, please pay attention to the PHP Chinese website !


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!