转置列表的列表
让我们来:
l = [[1,2,3],[4,5,6],[7,8,9]] 我正在寻找的结果是
 r = [[1,4,7],[2,5,8],[3,6,9]] 
并不是
 r = [(1,4,7),(2,5,8),(3,6,9)] 
非常感激
怎么样
 map(list, zip(*l)) --> [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 
对于Python 3.X的用户呢
 list(map(list, zip(*l))) 
一种方法是用NumPy转置。 对于一个列表,a:
 >>> import numpy as np >>> np.array(a).T.tolist() [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 
或另一个没有zip的:
 >>> map(list,map(None,*a)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 
等同于耶拿的解决scheme:
 >>> l=[[1,2,3],[4,5,6],[7,8,9]] >>> [list(i) for i in zip(*l)] ... [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 
只是为了好玩,有效的矩形和假设m [0]存在
 >>> m = [[1,2,3],[4,5,6],[7,8,9]] >>> [[row[i] for row in m] for i in range(len(m[0]))] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 
这些方法都可以在Python 2或3以及不均匀或矩形列表中使用:
设置
 import itertools import six list_list = [[1,2,3], [4,5,6, 6.1, 6.2, 6.3], [7,8,9]] 
方法1
 >>> map(list, six.moves.zip_longest(*list_list, fillvalue='-')) [[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']] 
  six.moves.zip_longest()变成 
-   Python 2中的itertools.izip_longest()
-   Python 3中的itertools.zip_longest()
 默认填充值是None 。 感谢@ jena的回答 ,其中map()将内部元组更改为列表。 这里将迭代器变成列表。 感谢@ Oregano's和@ badp的评论 。 
方法2
 >>> [list(row) for row in six.moves.zip_longest(*list_list, fillvalue='-')] [[1, 4, 7], [2, 5, 8], [3, 6, 9], ['-', 6.1, '-'], ['-', 6.2, '-'], ['-', 6.3, '-']] 
@ inspectorG4dget替代 。
方法3
 >>> map(list, map(None, *list_list)) [[1, 4, 7], [2, 5, 8], [3, 6, 9], [None, 6.1, None], [None, 6.2, None], [None, 6.3, None]] 
非凡的@SiggyF第二个select与不均匀的名单(不同于他的第一个,numpy转置,通过不均匀的名单),但None是唯一方便的填写价值。
(不,传递给内部map()的None不是fill值,这意味着别的东西,这意味着没有函数来传递行)。
三个选项可供select:
1.与Zip的地图
 solution1 = map(list, zip(*l)) 
2.清单理解
 solution2 = [list(i) for i in zip(*l)] 
3.循环附加
 solution3 = [] for i in zip(*l): solution3.append((list(i))) 
并查看结果:
 print(*solution1) print(*solution2) print(*solution3) # [1, 4, 7], [2, 5, 8], [3, 6, 9] 
也许不是最优雅的解决scheme,但是这是一个使用嵌套while循环的解决scheme:
 def transpose(lst): newlist = [] i = 0 while i < len(lst): j = 0 colvec = [] while j < len(lst): colvec.append(lst[j][i]) j = j + 1 newlist.append(colvec) i = i + 1 return newlist 
  #Import functions from library from numpy import size, array #Transpose a 2D list def transpose_list_2d(list_in_mat): list_out_mat = [] array_in_mat = array(list_in_mat) array_out_mat = array_in_mat.T nb_lines = size(array_out_mat, 0) for i_line_out in range(0, nb_lines): array_out_line = array_out_mat[i_line_out] list_out_line = list(array_out_line) list_out_mat.append(list_out_line) return list_out_mat 
这是一个转换不一定是正方形的列表清单的解决scheme:
 maxCol = len(l[0]) for row in l: rowLength = len(row) if rowLength > maxCol: maxCol = rowLength lTrans = [] for colIndex in range(maxCol): lTrans.append([]) for row in l: if colIndex < len(row): lTrans[colIndex].append(row[colIndex])