如何转置列表? [英] How do I transpose a List?
本文介绍了如何转置列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个列表[[1,2,3],[4,5,6]]
我如何转置它们,以便它们成为:[[1, 4], [2, 5], [3, 6]]
?
How do I transpose them so they will be: [[1, 4], [2, 5], [3, 6]]
?
我必须使用zip
功能吗? zip
函数是最简单的方法吗?
Do I have to use the zip
function? Is the zip
function the easiest way?
def m_transpose(m):
trans = zip(m)
return trans
推荐答案
使用 zip
和 *splat
是纯Python中最简单的方法.
Using zip
and *splat
is the easiest way in pure Python.
>>> list_ = [[1,2,3],[4,5,6]]
>>> zip(*list_)
[(1, 4), (2, 5), (3, 6)]
请注意,您会在内部使用元组而不是列表.如果需要列表,请使用map(list, zip(*l))
.
Note that you get tuples inside instead of lists. If you need the lists, use map(list, zip(*l))
.
如果您愿意使用numpy
而不是列表列表,则使用.T
属性更加容易:
If you're open to using numpy
instead of a list of lists, then using the .T
attribute is even easier:
>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> print(*a)
[1 2 3] [4 5 6]
>>> print(*a.T)
[1 4] [2 5] [3 6]
这篇关于如何转置列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文