Home >Backend Development >Python Tutorial >python中二维阵列的变换实例

python中二维阵列的变换实例

WBOY
WBOYOriginal
2016-06-16 08:41:151692browse

本文实例讲述了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, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
_-------------------------------------------------
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

这里解释一下:

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]))]
内层推导改变的是(从行中)选出的元素, 外层推导则影响了选择子(即列)

希望本文所述对大家的Python程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn