1

I think this may be a rather simple question but I've searched other questions and haven't really found anything completely relevant.

Say I have a list containing a number of strings like

mylist = ['queen', 'jack', 'queen', 'king', 'jack']

Now, I want to sort the strings in this list based on their relative values. So let's say king = 3, queen = 2, jack = 1.

What is the simplest way to associate those values with the strings in the list and sort them accordingly?

1 Answer 1

4

Use a key lookup:

suits = {'queen': 2, 'jack': 1, 'king': 2}
l = ['queen','jack','king']
print sorted(l, key=suits.get)
Sign up to request clarification or add additional context in comments.

7 Comments

@samplebias: Nooooo you beat me to it!
can you explain this notation? key=lambda x: suits[x], what is x?
x is the argument to the anonymous function created by the lambda statement, see docs.python.org/tutorial/controlflow.html#lambda-forms
@phooji sorry about that. this is crazy sometimes, huh? the flood of answers on some of these basic questions feels like a herd of dolphins diving into a bait ball @andrew's right on the money, lambda is an anon function.
Can be written without clunky lambda: sorted(l, key=suits.get).
|

Your Answer

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