Matrix Transpose in Python

前端 未结 18 1531
甜味超标
甜味超标 2020-11-22 00:21

I am trying to create a matrix transpose function for python but I can\'t seem to make it work. Say I have

theArray = [[\'a\',\'b\',\'c\'],[\'d\',\'e\',\'f\         


        
18条回答
  •  一个人的身影
    2020-11-22 01:15

    To complete J.F. Sebastian's answer, if you have a list of lists with different lengths, check out this great post from ActiveState. In short:

    The built-in function zip does a similar job, but truncates the result to the length of the shortest list, so some elements from the original data may be lost afterwards.

    To handle list of lists with different lengths, use:

    def transposed(lists):
       if not lists: return []
       return map(lambda *row: list(row), *lists)
    
    def transposed2(lists, defval=0):
       if not lists: return []
       return map(lambda *row: [elem or defval for elem in row], *lists)
    

提交回复
热议问题