Sort a list based on an another list
Sorting a list based on another list sorts the elements of the first list by the value of the element in the same position in the second list.
For example, sorting ["new", "hold", "close"] based on ['hold', 'close', 'withdraw', 'new', 'deposit', 'rollin', 'rebalance', 'switch'] results in ["hold", "close", "new"].
Call sorted on your list passing in argument the function that will perform the sorting.
Let's define the base list used as a reference for the sorting:
<:let base_list = ['hold', 'close', 'withdraw', 'new', 'deposit', 'rollin', 'rebalance', 'switch']:>
<:let my_list = ["new", "hold", "close"]:>
<:let my_sorted_list = sorted(my_list , key=lambda x: base_list.index(x) if x in base_list else x):>
The function returns the position of each element of my_list from base_list in order to perform the sorting
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article