文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [2004-08-11 01:36:37]

1. 变换二维数组

1.17 Transposing Two-Dimensional Arrays 变换二维数组

Credit: Steve Holden

1.1. 问题 Problem

You need to transpose a list of lists, turning rows into columns and vice versa.

你需要变换一个列表的列表,把行转换成列,反之亦然。

1.2. 解决 Solution

You must start with a list whose items are lists all of the same length:

你必须用一个元素是相同长度的list的list来开始

   1 arr = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]

A list comprehension offers a simple, handy way to transpose it:

一个list内涵提供一个简单,便利的方法去变换它

print [[r[col] for r in arr] for col in range(len(arr[0]))] 
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] 

1.3. 讨论 Discussion

This recipe shows a concise way (although not necessarily the fastest way) to turn rows into columns. List comprehensions are known for being concise.

这个配方显示一个简练的方法(尽管不是最快方法)去把行转换成列。List内涵以简练而闻名

Sometimes data just comes at you the wrong way. For instance, if you use Microsoft's ADO database interface, due to array element ordering differences between Python and Microsoft's preferred implementation language (Visual Basic), the GetRows method actually appears to return database columns in Python, despite its name. This recipe's solution to this common problem was chosen to demonstrate nested list comprehensions.

有时候,数据在你的错误方法上到来。例如,如果你使用微软的ADO数据库接口。由于数组元素的顺序在python和微软的首选语言(Visual Basic)之间不同。在python中, GetRows方法实际上出现来返回数据库的列, 而不管它的名字。对于这个普通的问题这个配方的解决方案被选择来证明嵌套的list内涵。

Notice that the inner comprehension varies what is selected from (the row), while the outer comprehension varies the selector (the column). This process achieves the required transposition.

注意到, 当外部的内涵改变选择器(列)的时候,内部的内涵改变被选择的(行),这个过程达到了所需要的变换。

If you're transposing large arrays of numbers, consider Numeric Python and other third-party packages. Numeric Python defines transposition and other axis-swinging routines that will make your head spin.

如果你正在变换很多大的数组, 考虑Numeric Python和其他第三方的包。Numeric Python定义了变换和其他让你头晕的轴变换的程序

1.4. 参考 See Also

The Reference Manual section on list displays (the other name for list comprehensions); Numeric Python (http://www.pfdubois.com/numpy/).