Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping track of original indicies when sorting a list of lists by length

You can sort a list of lists by length as follows:

l1 = [1,2,3]
l2 = [1,2,3]
l3 = [1,2]
lists = [l1, l2, l3]
sorted_lists = sorted(lists, key=len)
print sorted_lists  #[[1,2], [1,2,3], [1,2,3]]

I can't figure out how to keep track of the indicies to then match up the contents of sorted_lists with the original list names l1, l2 and l3.

This gets close, but I'm not sure how the solution can be implemented when sorting by length.

like image 275
John Crow Avatar asked Jun 21 '17 22:06

John Crow


2 Answers

It is very possible. Just modify the key a bit to specify the right predicate on which len is to be applied.

>>> lists = [l1, l2, l3]
>>> lists = sorted(enumerate(lists), key=lambda x: len(x[1])) # enumerate is a tuple of (index, elem), sort by len(elem)
[(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]
like image 56
cs95 Avatar answered Sep 30 '22 02:09

cs95


Using arg.sort() from numpy with list comprehension can be other way:

import numpy

new_list = [(index, lists[index])for index in numpy.argsort(lists)]
print(new_list)

Output:

[(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]
like image 36
student Avatar answered Sep 30 '22 03:09

student