pythonlistsublistreorganize

Break the sublists with Python


Here's the list I want to break:

    List A = [[[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]]], [[[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]]]]

List A has 2 sublists, each of which contains 3 pairs of coordinates. I'm wondering if I could keep the order of those coordinates, but regroup a pair of coordinate as a sublist. So here's the desired output:

    List B = [[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]]]

Thanks!!


Solution

  • You can convert it to a numpy array, reshape it, and then convert it back.

    import numpy as np
    
    A = [[[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]]], [[[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]]]]
    
    npA = np.array(A)
    
    B = npA.reshape(6, 2, 2).tolist()
    

    Or, if you want it to generalize to different input sizes

    B = npA.reshape(npA.size // 4, 2, 2).tolist()