用法2:二维矩阵变换(矩阵的行列互换)
>>> l1=[[1,2,3],[4,5,6],[7,8,9]] >>> print([[j[i] for j in l1] for i in range(len(l1[0])) ]) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] >>> zip(*l1) <zip object at 0x7f5a22651f88> >>> for i in zip(*l1): ... print(i) ... (1, 4, 7) (2, 5, 8) (3, 6, 9)
map函数:
map(function,iterable,...)
map函数接收的第一个参数为一个函数,能够为系统函数例如float,或者def定义的函数,或者lambda定义的函数都可。
举一个例子,下面这个例子在Python2.7下是能够正常显示的:
ls = [1,2,3] rs = map(str,ls) # 打印结果 ['1','2','3'] lt = [1,2,3,4,5,6] def add(num): return num + 1 rs = map(add, lt) print rs # [2,3,4,5,6,7]
可是在Python3下咱们输入:
>>> ls = [1,2,3] >>> rs = map(str,ls) >>> print(rs) <map object at 0x10d161898>
而不是咱们想要的结果,这也是Python3下发生的一些新的变化,若是咱们想获得须要的结果须要这样写:
ls=[1,2,3] rs=map(str,ls) print(list(rs))
这样显示的结果即为咱们想要看到的。