Q:

python nested lists and arrays

I have an output from a code where coordinates of several rectangles (four corners x,y) are provided in a list of arrays containing nested lists, which looks as follows: 
[array([[[x1, y1],
        [x2, y2],
        [x3, y3],
        [x4, y4]]], dtype=float32), 
...
array([[[x1, y1],
        [x2, y2],
        [x3, y3],
        [x4, y4]]], dtype=float32)]

I have another list of corresponding rectangle IDs. which looks like that :
[[310]
 [401]
...
 [203]
 [181]]

They are in the same order as the coordinates.
I want to mashup both lists to get the following data structure:
[[rect_ID, [(x1,y1),(x2,y2),(x3,y3),(x4,y4)],
[rect_ID, [(x1,y1),(x2,y2),(x3,y3),(x4,y4)],
...
[rect_ID, [(x1,y1),(x2,y2),(x3,y3),(x4,y4)]]

I need then to sort the list by the rect_ID
Any ideas how to achieve that?

A:

Here is one way of doing it using list comprehensions. 
Explanation: You loop over the combination of two lists (coords and ids) since they map one to one. i[0] gives you the index and j.flatten() converts each array of your coords into a single 1d array. The task then is to create pairs of coordinates as tuples. To do so, first you get every even indexed elements starting from 0 in steps of 2 using [0::2] and every odd indexed element starting from 1 in steps of 2 using [1::2]. Using zip, you combine them in pairs and then finally use list to convert them into a list []. 
Finally you sort the final list using the id (first element) as the key. 
# Sample data (Just taken for example purpose)
coords = [np.array([[[1, 2],
        [2,1],
        [3,2],
        [4,4]]]), 

np.array([[[3,2],
        [1,2],
        [1,4],
        [5,6]]]),

np.array([[[12,2],
        [1,21],
        [1,14],
        [15,6]]])]

ids = [[310],
 [181],[123]]

Code
final = [[i[0], list(zip(j.flatten()[0::2], j.flatten()[1::2]))] for i, j in zip(ids, coords)]

result = sorted(final, key=lambda x: x[0])
print (result)

Output
[[123, [(12, 2), (1, 21), (1, 14), (15, 6)]],
[181, [(3, 2), (1, 2), (1, 4), (5, 6)]],
[310, [(1, 2), (2, 1), (3, 2), (4, 4)]]]

