3

所以我在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]]

最好的方法是什么,最有效的方法是什么?我对编程很陌生,很抱歉成为菜鸟。谢谢。

4

4 回答 4

10

You can do it like that:

zip(*your_list)

Proof:

>>> 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)]
于 2012-09-22T05:46:38.000 回答
8

Check out numpy library. You can put your list into an array and transpose it like this:

a = array ([[1,2,3,4],
       [2,4,5,1],
       [3,4,6,2],
       [2,3,4,5]])
a.transpose()

P.S.: Explanation of Tadeck's solution is very easy. zip has the following signature:

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

So, it takes a number of sequences (we don't know how much exactly) and then builds tuples in the following order: takes first element of every sequence ant puts them in the tuple, then takes second element of every sequence and puts them in the second tuple and so on. It returns list of all tuples it build during its execution.

*lst - is, in fact, unpacking of arguments list. You can read more about it in the following note.

I hope, now everyone understands how this pretty piece of code works. :)

于 2012-09-22T05:47:44.330 回答
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截断为最短的长度。您可以使用 'map' 或itertools.izip_longestNone.

于 2012-09-22T06:38:59.920 回答
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]))]
于 2012-09-22T06:11:15.987 回答