Reputation: 1
Input
cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"]
Required Output
[2,3,5,6,8,'Jack','Queen','King']
I was able to sort it using this method, but i guess this isn't a one-loop only solution. does someone else have any guesses?
a= ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen','King','Jack','Queen']
for i in range(len(a)):
if a[i]=='Jack':
a[i]=11
elif a[i]=='Queen':
a[i]=12
elif a[i]=='King':
a[i]=13
a.sort()
Upvotes: 0
Views: 43
Reputation: 1530
Code:
cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
sorted(set(MyList), key = lambda x: cards.index(str(x)[0]))
Output:
[2, 3, 5, 6, 8, 'Jack', 'Queen', 'King']
Upvotes: 0
Reputation: 71522
Create a dict with values for the non-numeric cards, and use its get
method to create a key
function for sort
/sorted
.
>>> ranks = {'Jack': 11, 'Queen': 12, 'King': 13}
>>> cards = ['Jack', 8, 2, 6, 'King', 5, 3, 'Queen', "Jack", "Queen", "King"]
>>> sorted(cards, key=lambda c: ranks.get(c, c))
[2, 3, 5, 6, 8, 'Jack', 'Jack', 'Queen', 'Queen', 'King', 'King']
Upvotes: 2