读书人

python中二维阵列的转换

发布时间: 2013-09-28 10:01:20 作者: rapoo

python中二维阵列的变换

先上代码:

arr = [ [1, 2, 3], [4, 5, 6], [7, 8,9], [10, 11, 12]]print map(list, zip(*arr))print '_----------------------------------'print [[r[col] for r in arr] for col in range(len(arr[0]))]

解释一下:

1. 第一种方法:map(list, zip(*arr))

zip([iterable,...])

This function returns a list of tuples, where the i-th tuple contains thei-th element from each of the argument sequences or iterables.

zip()

这个函数返回一个元组的列表,其中的第i个元组包含从参数传进来的队列的每一个参数的元素的的第I个元素


翻译的太没脸见人了,给个例子说明一下吧

>>> x = [1, 2, 3]>>> y = [4, 5, 6]>>> zipped = zip(x, y)>>> zipped[(1, 4), (2, 5), (3, 6)]

实际上zip(*arr)返回的就是[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)],只不过它的每个元素是元组


map(func, list):

对list中的每个元素调用func方法,返回列表

参数*arr 是python用于传递任意基于位置的参数的语法


2. 第二种方法 [[r[col] for r in arr] for col in range(len(arr[0]))]

内层推导改变的是(从行中)选出的元素, 外层推导则影响了选择子(即列)

读书人网 >perl python

热点推荐