-1

When we sort a dictionary by value in Python, we use lambda func. But i tried this way in my lists, instead of values, using another list index number. This may be a short str function/method for my question.

Here is an example:

cardsorder = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
colors = ['C', 'D', 'S', 'H']
handEx = ['8C','TS','KC','9H','4S']

I want to sort my handEx list elements by using cardsorder index numbers. Firstly i scan every element and i find values for sorting:

for card in handEx:
    value = cardsorder.index(card[0])

In this way by using these values, i can sort elements by comparing the others but i think it is a very long way to find the solution. Is there a simpler solution, for example using a lambda function?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
N.S.Genez
  • 27
  • 6

1 Answers1

2

You're very close. Just make a key function that gets the equivalent of value:

>>> sorted(handEx, key=lambda card: cardsorder.index(card[0]))
['4S', '8C', '9H', 'TS', 'KC']

Or in-place:

handEx.sort(key=lambda card: cardsorder.index(card[0]))

By the way, I posted a similar answer here.

wjandrea
  • 28,235
  • 9
  • 60
  • 81