Ask Your Question
0

Combining and sorting multiple enumerated lists

asked 4 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 4 years ago

Sébastien gravatar image

updated 4 years ago

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']
Preview: (hide)
link

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: 4 years ago

Seen: 311 times

Last updated: Nov 08 '20