5

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
John Crow
  • 927
  • 3
  • 13
  • 26

2 Answers2

8

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])]
cs95
  • 379,657
  • 97
  • 704
  • 746
1

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])]
niraj
  • 17,498
  • 4
  • 33
  • 48
  • 1
    Seems fine. As for speed, they'd both be the same since they both internally run on C routines. – cs95 Jun 21 '17 at 23:04