pythontranspose

How do I transpose rows to columns with a triangular array?


I want to convert a lower triangle to an upper triangle so that the rows become columns. I have the following list of lists:

[[-1]
 [-2, -2]
 [-2, -1, -2]
 [-3, 0, -1, -3
 [-3, 2, 1, -1, -3]
 [-4, 4, 3, 1, -1, -4]
 [-4, 7, 6, 4, 2, -1, -4]
 [-5, 10, 9, 7, 5, 2, -1, -5]
 [-5, 14, 13, 11, 9, 6, 3, -1, -5]
 [-6, 18, 17, 15, 13, 10, 7, 3, -1, -6]
 [-6, 23, 22, 20, 18, 15, 12, 8, 4, -1, -6]
 [-7, 28, 27, 25, 23, 20, 17, 13, 9, 4, -1, -7]
 [-7, 34, 33, 31, 29, 26, 23, 19, 15, 10, 5, -1, -7]
 [-8, 40, 39, 37, 35, 32, 29, 25, 21, 16, 11, 5, -1, -8]
 [-8, 47, 46, 44, 42, 39, 36, 32, 28, 23, 18, 12, 6, -1, -8]
 [-9, 54, 53, 51, 49, 46, 43, 39, 35, 30, 25, 19, 13, 6, -1, -9]
 [-9, 62, 61, 59, 57, 54, 51, 47, 43, 38, 33, 27, 21, 14, 7, -1, -9]
 [-10, 70, 69, 67, 65, 62, 59, 55, 51, 46, 41, 35, 29, 22, 15, 7, -1, -10]]

Do I need to pad the rows with zeros so that zip can do this?


Solution

  • You don't have to pad if you use itertools.zip_longest, it'll do the padding for you, but then you'll have to filter yourself:

    In [7]: data
    Out[7]:
    [[-1],
     [-2, -2],
     [-2, -1, -2],
     [-3, 0, -1, -3],
     [-3, 2, 1, -1, -3],
     [-4, 4, 3, 1, -1, -4],
     [-4, 7, 6, 4, 2, -1, -4],
     [-5, 10, 9, 7, 5, 2, -1, -5],
     [-5, 14, 13, 11, 9, 6, 3, -1, -5],
     [-6, 18, 17, 15, 13, 10, 7, 3, -1, -6],
     [-6, 23, 22, 20, 18, 15, 12, 8, 4, -1, -6],
     [-7, 28, 27, 25, 23, 20, 17, 13, 9, 4, -1, -7],
     [-7, 34, 33, 31, 29, 26, 23, 19, 15, 10, 5, -1, -7],
     [-8, 40, 39, 37, 35, 32, 29, 25, 21, 16, 11, 5, -1, -8],
     [-8, 47, 46, 44, 42, 39, 36, 32, 28, 23, 18, 12, 6, -1, -8],
     [-9, 54, 53, 51, 49, 46, 43, 39, 35, 30, 25, 19, 13, 6, -1, -9],
     [-9, 62, 61, 59, 57, 54, 51, 47, 43, 38, 33, 27, 21, 14, 7, -1, -9],
     [-10, 70, 69, 67, 65, 62, 59, 55, 51, 46, 41, 35, 29, 22, 15, 7, -1, -10]]
    
    In [8]: t = itertools.zip_longest(*data)
    
    In [9]: [[x for x in sub if x is not None] for sub in t]
    Out[9]:
    [[-1, -2, -2, -3, -3, -4, -4, -5, -5, -6, -6, -7, -7, -8, -8, -9, -9, -10],
     [-2, -1, 2, 4, 7, 10, 14, 18, 23, 28, 34, 40, 47, 54, 62, 70],
     [-2, -1, 1, 3, 6, 9, 13, 17, 22, 27, 33, 39, 46, 53, 61, 69],
     [-3, -1, 1, 4, 7, 11, 15, 20, 25, 31, 37, 44, 51, 59, 67],
     [-3, -1, 2, 5, 9, 13, 18, 23, 29, 35, 42, 49, 57, 65],
     [-4, -1, 2, 6, 10, 15, 20, 26, 32, 39, 46, 54, 62],
     [-4, -1, 3, 7, 12, 17, 23, 29, 36, 43, 51, 59],
     [-5, -1, 3, 8, 13, 19, 25, 32, 39, 47, 55],
     [-5, -1, 4, 9, 15, 21, 28, 35, 43, 51],
     [-6, -1, 4, 10, 16, 23, 30, 38, 46],
     [-6, -1, 5, 11, 18, 25, 33, 41],
     [-7, -1, 5, 12, 19, 27, 35],
     [-7, -1, 6, 13, 21, 29],
     [-8, -1, 6, 14, 22],
     [-8, -1, 7, 15],
     [-9, -1, 7],
     [-9, -1],
     [-10]]