Ask Your Question
0

How to organize a list according to an other list

asked 2020-07-02 09:02:26 +0200

Cyrille gravatar image

updated 2020-07-02 09:12:14 +0200

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2020-07-02 09:45:48 +0200

tmonteil gravatar image

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).

edit flag offensive delete link more

Comments

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

Cyrille gravatar imageCyrille ( 2020-07-02 11:17:05 +0200 )edit

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

tmonteil gravatar imagetmonteil ( 2020-07-02 11:31:53 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2020-07-02 09:02:26 +0200

Seen: 209 times

Last updated: Jul 02 '20