简体   繁体   English

最pythonic的矩阵换位

[英]the most pythonic matrix transposition

the definition: 定义:

def transpose(matrix):
  return [[i[j] for i in matrix] for j in range(0, len(matrix[0]))]

and few examples: 和几个例子:

>>> transpose([[2]])
[[2]]
>>> transpose([[2, 1]])
[[2], [1]]
>>> transpose([[2, 1], [3, 4]])
[[2, 3], [1, 4]]
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']])
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]

is there any better way to implement that? 有没有更好的方法来实现呢?

If you convert to a numpy array you can just use the T: 如果转换为numpy数组,则可以使用T:

>>> import numpy as np
>>> a = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> a = np.asarray(a)
>>> a
array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']],
      dtype='|S1')
>>> a.T
array([['a', 'd', 'g'],
       ['b', 'e', 'h'],
       ['c', 'f', 'i']],
      dtype='|S1')

Use zip with * : 使用带* zip

>>> lis = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> zip(*lis)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

If you want a list of lists: 如果要列表列表:

>>> [list(x) for x in zip(*lis)]
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]

Use itertools.izip for memory efficient solution: 使用itertools.izip获得内存有效的解决方案:

>>> from itertools import izip
>>> [list(x) for x in izip(*lis)]
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM