Vatec
Vatec

Reputation: 43

Python: sort list of strings in order that they appear in another string

I am looking for a way to sort a list in order of appearance in another string, so that the the follow code

thelist = ["a", "b", "c"]
thestring = "b c a"

will be able to be sorted into

["b", "c", "a"]

as that is the order that each of the list objects appear in the string.

How would I go about achieving this? Would it be possible to use the sorted function with certain param to easily achieve this or something else? Thanks.

Upvotes: 3

Views: 2244

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121614

Turn your string into a map:

indices = {c: i for i, c in enumerate(thestring.split())}

then sort using that map:

sorted(thelist, key=indices.get)

This allows for values from thestring missing in thelist as well as vice-versa. This also works correctly for repeating elements in thelist.

Demo:

>>> thestring = "b c a"
>>> indices = {c: i for i, c in enumerate(thestring.split())}
>>> sorted(['a', 'b', 'c'], key=indices.get)
['b', 'c', 'a']
>>> sorted(['a', 'b', 'c', 'a', 'c', 'b'], key=indices.get)
['b', 'b', 'c', 'c', 'a', 'a']
>>> sorted(['a', 'a', 'a'], key=indices.get)
['a', 'a', 'a']
>>> sorted(['a', 'e', 'b'], key=indices.get)
['e', 'b', 'a']

Upvotes: 6

Related Questions