3

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.

5
  • 2
    Just use thestring.split(), instead of sorting thelist? Commented Aug 17, 2014 at 2:05
  • You could try .sort(key=lambda c: thestring.index(c)), but that won't deal with repeats nicely Commented Aug 17, 2014 at 2:05
  • Yes I would need to be able to sort where there are multiple, any other way? Commented Aug 17, 2014 at 2:06
  • @Vatec this is a non-deterministic sorting when characters are repeated! (or in other words - you can't...) Commented Aug 17, 2014 at 2:08
  • @Vatec: multiple what? Repeated elements in thelist? Or repeats in thestring? In which case what position wins? Commented Aug 17, 2014 at 2:08

1 Answer 1

6

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']
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, this would work except thestring will not always be seperated by spaces, it could be "ycyby" which needs to produce ["c", b"]
@Vatec: then use {c: i for i, c in enumerate(thestring)}, the exact integer values don't really matter.
@Vatec: Perhaps in future you could be a bit more clear on such requirements?
Thank you, sorry I am new to python and stackoverflow I will be more clear next time
Perfect answer!! (Windows server 2012 R2; Python 3.7)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.