0

I have a list of strings:

cards = ['2S', '8D', '8C', '4C', 'TS', '9S', '9D', '9C', 'AC', '3D']

and the order in which I want to display the cards:

CARD_ORDER = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']

This is how I'm trying to order the list:

sorted(cards, lambda x,y: CARD_ORDER.index(x[0]) >= CARD_ORDER.index(y[0]) )

Unfortunately this does not seem to work....

or more precisely the list stays exactly the same, sorted(cards) works fine instead.

Any ideas?

2 Answers 2

8

it's

sorted(cards, key=lambda x: CARD_ORDER.index(x[0]))

key parameter accepts a single value, by which to sort the main iterable. You're probably trying to use cmp parameter which is not recommended for quite some time.

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

2 Comments

that works thanks, any explanation why the other way does not work?
@RadiantHex, because you are using >= which only returns False or True (0 or 1), whereas the comparison function is expected to return -1, 0 or 1.
2

Try

sorted(cards, key = lambda x: CARD_ORDER.index(x[0]) )

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.