Track original pointers when sorting a list of lists by length

You can sort the 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 cannot figure out how to track indicators, and then map the contents sorted_liststo the names of the original list l1, l2and l3.

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

+4
source share
2 answers

It is very possible. Just change the key a bit to indicate the correct predicate to apply to len.

>>> 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])]
+8
source

arg.sort() numpy list comprehension :

import numpy

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

:

[(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]
+1

Source: https://habr.com/ru/post/1679846/


All Articles