Home > Blockchain >  Sorting multiple lists to get a single organised list
Sorting multiple lists to get a single organised list

Time:08-22

I have multiple lists with coordinates:

x = [2423, 2342, 4432]
 
y = [532, 5432, 5432] 

w = [7456, 256, 5645] 

h = [2345, 6543, 8764] 

I want to concatenate these lists so that the position of an item would correspond with the position of other items in a single list. You can think of it as a dataset for every item in x, y, w, h with the same position in the same list

for example:

Boxes = [
[x[0],y[0],w[0],h[0]],
[x[1],y[1],w[1],h[1]],
[x[2],y[2],w[2],h[2]],
]

Of course I would not write manually the position of an element for every list, but this shows what I want to achieve. Any help would be appreciated

CodePudding user response:

Alternatviely, you try to do this by List Comprehension in zipping way: (it's prob. more efficient for big lists... and don't have to use index to access each item in lists.)

Inspired by @Mechanic... sharing the credit? ;-)


x = [2423, 2342, 4432]
y = [532, 5432, 5432] 
w = [7456, 256, 5645] 
h = [2345, 6543, 8764] 
    
Boxes = []

Boxes = [[a, b, c, d] for a, b, c, d in zip(x, y, w, h)]
print(Boxes)

# OR as @Mechanic suggested and posted earlier, you can try this too (even more *elegant* and *less typing*): 

outs = [list(tp) for tp in zip(x, y, w, h)]    # tuple for all 4 items

CodePudding user response:

After setting the coordinates dynamically, you can append them into the boxes one by one using the for loop with the length of the x. Please note length of all arrays should be the same.

x = [2423, 2342, 4432]
y = [532, 5432, 5432] 
w = [7456, 256, 5645] 
h = [2345, 6543, 8764] 

Boxes = []

for i in range(len(x)):
    Boxes.append([x[i], y[i], w[i], h[i]])

After this Boxes value would be equal to that:

[[2423, 532, 7456, 2345], [2342, 5432, 256, 6543], [4432, 5432, 5645, 8764]]
  • Related