代码区项目交易流程

Transposing a matrix into Python


I'm trying to create a matrix transpose function in python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the height of the matrix is 2 and the width is 3):

A=[[1, 2, 3], [4, 5, 6]]

To be transposed the the jth item in the ith index should become the ith item in the jth index. Here's how the above sample would look transposed:

>>> transpose([[1, 2, 3], [4, 5, 6]]) [[1, 4], [2, 5], [3, 6]] >>> transpose([[1, 2], [3, 4]]) [[1, 3], [2, 4]]

How can I do this?

You can use zip with * to get transpose of a matrix:

>>> A = [[ 1, 2, 3],[ 4, 5, 6]] >>> zip(*A) [(1, 4), (2, 5), (3, 6)] >>> lis = [[1,2,3], ... [4,5,6], ... [7,8,9]] >>> zip(*lis) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you want the returned list to be a list of lists:

>>> [list(x) for x in zip(*lis)] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] #or >>> map(list, zip(*lis)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

点击收藏

LAST Python Data: Quick Tip: Comparing two pandas dataframes and getting the differen ... Python Lands on the Windows 10 App Store NEXT