Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting list based on order of substrings in another list

I have two lists of strings.

list_one = ["c11", "a78", "67b"]
list_two = ["a", "b", "c"]

What is the shortest way of sorting list_one using strings from list_two to get the following output?

["a78", "67b", "c11"]

Edit 1: There is a similar question Sorting list based on values from another list?, but in that question he already has the list of required indexes for resulting string, while here I have just the list of substrings.

Edit 2: Since the example of list above might be not fully representative, I add another case.

list_one is ["1.cde.png", "1.abc.png", "1.bcd.png"] list_two is ["abc", "bcd", "cde"]. The output is supposed to be [ "1.abc.png", "1.bcd.png", "1.cde.png"]

If, for example, list_one is shorter than list_two, it should still work:

list_one is ["1.cde.png", "1.abc.png"] list_two is ["abc", "bcd", "cde"] The output is supposed to be [ "1.abc.png", "1.cde.png"]

like image 223
Aliaksei Laurynovich Avatar asked Oct 24 '25 22:10

Aliaksei Laurynovich


1 Answers

key = {next((s for s in list_one if v in s), None): i for i, v in enumerate(list_two)}
print(sorted(list_one, key=key.get))

This outputs:

['a78', '67b', 'c11']
like image 200
blhsing Avatar answered Oct 27 '25 12:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!