python中 map() 与 zip() 的使用

mac2026-09-25  9

对于map()它的原型是:map(function,sequence),就是对序列sequence中每个元素都执行函数function操作。 比如之前的a,b,c = map(int,raw_input().split()),意思就是说把输入的a,b,c转化为整数。再比如:

a = ['1','2','3','4'] print map(list,a) print map(int,a) # 第一个map是把列表a中每个元素转化为列表,第二个map是把a中每个元素转化为整数。

而对于zip(),原型是zip(*list),list是一个列表,*zip(list)返回的是一个元组,比如:

list = [[1,2,3],[4,5,6],[7,8,9]] t = zip(*list) print t # 输出 [(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 # [(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)] >>> list = [[0,1,2],[3,1,4]] >>> [sum(x) for x in list] [3, 8] >>> map(sum,list) [3, 8] >>> 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] >>> 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]
最新回复(0)