Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list based on a given order [duplicate]

I have a list, say A = [[3,5],[1,3],[6,1]].

And I have another list, say B = [6,1,3]

I want to sort list A so that A becomes [[6,1],[1,3],[3,5]], which fits the given B — i.e. the first member of each A sublist should be sorted according to B.

like image 813
fxy Avatar asked Sep 22 '17 13:09

fxy


1 Answers

derive a dict mapping the numbers in B to their indices and use that in the sort key function. This way you keep the key function constant time.

>>> A = [[3,5],[1,3],[6,1]]
>>> B = [6,1,3]
>>> srt = {b: i for i, b in enumerate(B)}
>>> sorted(A, key=lambda x: srt[x[0]])
[[6, 1], [1, 3], [3, 5]]

There are certainly a few caveats to this code. If a number were repeated in B you would get the index for the last entry used in the sort.

Also if there is an entry in A not matched in B, you have a KeyError. You could mitigate this somewhat by using dict.get with some default value, but if your input data was screwed to begin with, an error is a good thing to receive.

like image 197
Paul Rooney Avatar answered Oct 16 '22 06:10

Paul Rooney