# How to organize a list according to an other list

Here is a problem that resists all my tentatives. Say I have 2 lists of same length

X=[1.1, 2.5, 5.0, 6.01, 12.5, 18.4, 7.8, 14.9, 20, 13.6]
Y=[13.1, 21.5, 53.0, 16.21, 2.45, 8.94, 4.18, 12.8, 17.7, 13.6]


The first one has already been organized in sublists

Xc=[[12.5, 5.0, 20], [7.8, 1.1, 18.4], [6.01, 14.9, 2.5, 13.6]]


What I want to achieve is to construct a list Yc composed of sublists such that if X [i] belongs to Xc[j], Y[i] belongs to Yc[j].

Ps I know that the title is a bad description of what I want to achieve.

edit retag close merge delete

Sort by ยป oldest newest most voted

For every sublist of Yc and every element a in X, search a in the sublist and append the corresponding element b in Y (X and Y are aligned with zip):

Yc = []
for j in Xc:
l = []
for (a,b) in zip(X,Y):
if a in j:
l.append(b)
Yc.append(l)


Note that this way, the elements in the sublists are not sorted in the same order (but i guess you do not mind given the description).

more

Thanks a lot tmonteil. It works as expected. Simply for my understanding of programming. Was it possible to do the same thing withou loops ?

( 2020-07-02 04:17:05 -0500 )edit

you can always hide loops, for example by replacing them with recursive calls of functions.

( 2020-07-02 04:31:53 -0500 )edit