1

I have a list as follows:

[['a', 123], ['b', 456], ['c', 789]]

and the string cba

I would like to sort the list based on the first item and the order in which the string cba is in:

[['c', 789], ['b', 456], ['a', 123]]

What would be the best way to go about this?

3
  • so you want descending order of the letters? Have you tried anything? Also its bad practice to mix types in lists. You should consider changing the collection type to tuple Commented Feb 16, 2017 at 3:37
  • So if the string were bca, you'd want [['b', 456], ['c', 789], ['a', 123]], right? Commented Feb 16, 2017 at 3:38
  • sorry if it's not clear, it's not just descending order based on the first item, but the order of the string as @ShadowRanger mentions Commented Feb 16, 2017 at 3:39

1 Answer 1

8

This works quite well with key-based use of list.sort/sorted:

mylist = [['a', 123], ['b', 456], ['c', 789]]
mykey = 'cba'

mylist.sort(key=lambda x: mykey.index(x[0]))

If the key string were huge, repeated index calls would be inefficient (make a dict that maps value to index in a single pass if that's an issue, e.g. mykeydict = {k: i for i, k in enumerate(mykey)}, then key=lambda x: mykeydict[x[0]]), but for short to moderate lengths, the index call is cheap enough (it's only performed once per item in mylist, not for every comparison).

Sign up to request clarification or add additional context in comments.

Comments

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.