Combining and sorting multiple enumerated lists

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

Sort by » oldest newest most voted

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']

more