所以我在python中有这个列表,
a= [[1,2,3,4],
[2,4,5,1],
[3,4,6,2],
[2,3,4,5]]
并希望将列表水平翻转为垂直。
b= [[1,2,3,2],
[2,4,4,3],
[3,5,6,4],
[4,1,2,5]]
最好的方法是什么,最有效的方法呢?我很喜欢编程,对不起是菜鸟。感谢。
答案 0 :(得分:10)
你可以这样做:
zip(*your_list)
证明:
>>> a = [[1, 2, 3, 4], [2, 4, 5, 1], [3, 4, 6, 2], [2, 3, 4, 5]]
>>> zip(*a)
[(1, 2, 3, 2), (2, 4, 4, 3), (3, 5, 6, 4), (4, 1, 2, 5)]
答案 1 :(得分:8)
查看numpy库。您可以将列表放入数组中并将其转置为:
a = array ([[1,2,3,4],
[2,4,5,1],
[3,4,6,2],
[2,3,4,5]])
a.transpose()
P.S。:解释Tadeck的解决方案非常简单。 zip
具有以下签名:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
因此,它需要许多序列(我们不知道究竟多少),然后按以下顺序构建元组:获取每个序列的第一个元素ant将它们放入元组中,然后获取每个序列的第二个元素,并将它们放在第二个元组中,依此类推。它返回它在执行期间构建的所有元组的列表。
*lst
- 实际上是解包参数列表。您可以在following note。
我希望,现在每个人都明白这段漂亮的代码是如何工作的。 :)
答案 2 :(得分:5)
您询问了效率。您可以使用timeit。
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]" "zip(*a)"
1000000 loops, best of 3: 0.569 usec per loop
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]" "map(None, *a)"
1000000 loops, best of 3: 0.644 usec per loop
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]" "[[row[i] for row in a] for i in xrange(len(a[0]))]"
1000000 loops, best of 3: 1.43 usec per loop
>python -m timeit -s "from numpy import array; a = array([[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]])" "a.transpose()"
1000000 loops, best of 3: 0.249 usec per loop
对于[[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]*1000000
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]*1000000" "zip(*a)"
10 loops, best of 3: 400 msec per loop
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]*1000000" "map(None, *a)"
10 loops, best of 3: 458 msec per loop
>python -m timeit -s "a = [[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]*1000000" "[[row[i] for row in a] for i in xrange(len(a[0]))]"
10 loops, best of 3: 770 msec per loop
>python -m timeit -s "from numpy import array; a = array([[1,2,3,4],[2,4,5,1],[3,4,6,2],[2,3,4,5]]*1000000)" "a.transpose()"
1000000 loops, best of 3: 0.251 usec per loop
如果您的列表长度不同,zip
会缩短到最短的长度。您可以使用“地图”或itertools.izip_longest
代替None
填充缺失值。
答案 3 :(得分:1)
另一种方式是:
a= [[1,2,3,4],
[2,4,5,1],
[3,4,6,2],
[2,3,4,5]]
a = [[row[i] for row in a] for i in range(len(a[0]))]