'Sorting a list of cards by face value [closed]
my input is:
cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen']
and the expected output is [2,3,5,6,8,'Jack','Queen','King'] but generic method mean always number comes first and then alphabets sequences comes.
Solution 1:[1]
You can use sorted with a helper dictionary and a custom key:
cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen']
# add other values (e.g. "Ace" if needed)
heads = {'Jack': 11, 'Queen': 12, 'King': 13}
sorted(cards, key=lambda x: heads.get(x, x))
output: [2, 3, 5, 6, 8, 'Jack', 'Queen', 'King']
The key is applied to the values before sorting, thus lambda x: heads.get(x,x) will get you either the value in heads if the key is present or return the value itself is the key is absent, then this is equivalent to sorting [11, 8, 2, 6, 13, 5, 3, 12]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
