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.
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])]
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])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With