简体   繁体   中英

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.

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM