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!