Indigo Snow
Indigo Snow

Reputation: 47

Sort lists of list of playing cards [python]

I have a list of lists with 3 playing cards in each list like so -

[['As', 'Qs', '7s'], ['Ad', 'Ks', '7s'], ['Ac', '9d', '8s']]

and I want my result to look like -

[['Ad', 'Ks', '7s'], ['As', 'Qs', '7s'], ['Ac', '9d', '8s']]

Note: the order is based on the rank of the cards. AKQJT9...

I was thinking of using a comparison key like this

values=dict(zip('23456789TJQKA',range(2,15)))

And then creating a new list by traversing the original list and inserting the new list of 3 cards at appropriate points.

Is there a better way to do this? Thanks.

Upvotes: 2

Views: 144

Answers (2)

Sadegh Sh
Sadegh Sh

Reputation: 36

This code should sort the cards as you wanted.

a= [['As', 'Qs', '7s'], ['Ad', 'Ks', '7s'], ['Ac', '9d', '8s']]
values=dict(zip('23456789TJQKA','abcdefghijklm'))
b=[[values[x[0]] for x in y] for y in a] 
# b = [['m', 'k', 'f'], ['m', 'l', 'f'], ['m', 'h', 'g']]
c=[''.join(x) for x in b] 
# c = ['mkf', 'mlf', 'mhg']
[x for _, x in sorted(zip(c, a), reverse=True)]
# x = [['Ad', 'Ks', '7s'], ['As', 'Qs', '7s'], ['Ac', '9d', '8s']]

Upvotes: 2

Jafar Isbarov
Jafar Isbarov

Reputation: 1562

Python has a built-in sort function, but it sorts numbers before strings:

>>> cards = [['As', 'Qs', '7s'], ['Ad', 'Ks', '7s'], ['Ac', '9d', '8s']]
>>> sorted(cards)
[['Ac', '9d', '8s'], ['Ad', 'Ks', '7s'], ['As', 'Qs', '7s']]

You can pass a key argument to solve this:

>>> sorted(cards, key=lambda x: (x[0].isdigit(), x))
[['Ac', '9d', '8s'], ['Ad', 'Ks', '7s'], ['As', 'Qs', '7s']]

Check out this for the explanation: https://stackoverflow.com/a/24624700/11919175

Upvotes: 0

Related Questions