How can I efficiently sort nested lists by the first element of each nested list matching the order given in order list?
List of lists: [[97, 2, 0, 2], [97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6], [99, 3, 3, 6], [101, 1, 6, 7], [100, 1, 7, 8]]
Order list: [97, 98, 99, 99, 101, 100, 97, 99]
Desired list: [[97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6], [101, 1, 6, 7], [100, 1, 7, 8], [97, 2, 0, 2], [99, 3, 3, 6]]
Try creating a dict
keyed to the first value from your nested list. Then build the output list from that dict
:
nl = [[97, 2, 0, 2], [97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6],
[99, 3, 3, 6], [101, 1, 6, 7], [100, 1, 7, 8]]
# Associate first value in list to the list
d = {v[0]: v for v in nl}
order_lst = [97, 98, 99, 99, 101, 100, 97, 99]
# Grab the list associated to each value in order_list from d
out = [d[v] for v in order_lst]
print(out)
out
:
[[97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6], [101, 1, 6, 7],
[100, 1, 7, 8], [97, 2, 0, 2], [99, 3, 3, 6]]
*Note this assumes that all sub-lists in the nested list are acceptable values as multiple variants of the same key are not supported in a dict
.