Home > Enterprise >  Sorting a list of string using a custom order stored in another list
Sorting a list of string using a custom order stored in another list

Time:09-25

I have a list with 2 or 3 character strings with the last character being the same.

example_list = ['h1','ee1','hi1','ol1','b1','ol1','b1']

is there any way to sort this list using the order of another list.

order_list = ['ee','hi','h','b','ol']

So the answer should be something like example_list.sort(use_order_of=order_list)

I have found other questions on StackOverflow but I am still unable find a answer with a good explanation.

CodePudding user response:

You could build an order_map that maps the prefixes to their sorting key, and then use that map for the key when calling sorted:

example_list = ['h1','ee1','hi1','ol1','b1','ol1','b1']
order_list = ['ee','hi','h','b','ol']
order_map = {x: i for i, x in enumerate(order_list)}
sorted(example_list, key=lambda x: order_map[x[:-1]])

This has an advantage over calling order_list.index for each element, as fetching elements from the dictionary is fast.

You can also make it work with elements that are missing from the order_list by using dict.get with a default value. If the default value is small (e.g. -1) then the values that don't appear in order_list will be put at the front of the sorted list. If the default value is large (e.g. float('inf')) then the values that don't appear in order_list will be put at the back of the sorted list.

CodePudding user response:

You can use sorted with key using until the last string of each element in example_list:

sorted(example_list, key=lambda x: order_list.index(x[:-1]))

Ourput:

['ee1', 'hi1', 'h1', 'b1', 'b1', 'ol1', 'ol1']

Note that this assumes all element in example_list without the last character is in order_list

CodePudding user response:

Something like this? It has the advantage of handling duplicates.

sorted_list = [
    i
    for i, _
    in sorted(zip(example_list, order_list), key=lambda x: x[1])
]
  • Related