Break the sublists with Python

175 Views Asked by At

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!!

3

There are 3 best solutions below

0
duckboycool On BEST ANSWER

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()
0
doca On

For your specific requirement, You can take the first element of the list A and extend it with the second element of the list A

B = A[0]
B.extend(A[1])
0
BAE On

As for your specific question, we can get B from A[0]+A[1]

>>> 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]]]]
>>> 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]]]
>>> A[0] + A[1]
[[[0, 1], [2, 3]], [[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]], [[0, 3], [1, 2]], [[0, 2], [1, 3]]]
>>> A[0] + A[1] == B
True