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
.
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.
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