pythonlistplaying-cards

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.


Solution

  • 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']]