Ask Your Question
0

Combining and sorting multiple enumerated lists

asked 2020-11-08 07:12:02 +0100

nooniensoong97 gravatar image

Hi,

I have a bunch of lists that have been enumerated. I would like to combine them into a single list in the number order of the lists. For example: I have these lists a = [2,8,10], b = [0,3,5], c = [1,4,7], d = [6,9,11] I would like to combine them into one list like this [b,c,a,b,c,b,d,c,a,d,a,d]. However, due to my actual work all enumerated lists are of different lengths. Even a few of them are null sets at this time until I am ready to process a much bigger set.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2020-11-08 10:59:56 +0100

Sébastien gravatar image

updated 2020-11-08 11:01:40 +0100

The following function:

def merge_structure(lists): 
    s = sorted((a,i) for i,L in enumerate(lists) for a in L) 
    return [i for (a,i) in s]

allows to do:

sage: lists = [2,8,10], [0,3,5], [1,4,7], [6,9,11]                              
sage: merge_structure(lists)
[1, 2, 0, 1, 2, 1, 3, 2, 0, 3, 0, 3]

which can be translated from indices 0,1,2,3 to a,b,c,d as follows:

sage: d = dict(enumerate('abcd'))                                               
sage: [d[j] for j in merge_structure(lists)]                                              
['b', 'c', 'a', 'b', 'c', 'b', 'd', 'c', 'a', 'd', 'a', 'd']
edit flag offensive delete link more

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-11-08 07:12:02 +0100

Seen: 273 times

Last updated: Nov 08 '20