M Griggs February 2016

Python - sorting a list of tuples by an uneven list

I have a deck of cards built by the following code:

import itertools

suits = "DCHS"
ranks = "23456789TJQKA"

cardDeck = list(set(itertools.product(ranks, suits)))

I want to sort the deck of card by ranks. Doing a sorted(cardDeck, key=lambda x: x[0]) sorts the list by ranks alphabetically (23456789AJKQT) but I would like to find a way to maintain the order of ranks (23456789TJQKA).

I've been playing with trying to get a lambda function for the key= parameter that will iterate through the characters in the ranks string but so far I'm up against a wall. Maybe I need to make suits and ranks list of characters rather than strings?

Answers


Andrey February 2016

ranks = "23456789TJQKA"

values = {'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}

cardDeck.sort(key=lambda c: int(c[0]) if '2' <= c[0] <= '9' else values[c[0]])


Lego Stormtroopr February 2016

You already have the ranking in your ranks list. Just use that in your sorter:

print sorted(cardDeck, key=lambda x: ranks.index(x[0])) 

You can see the full thing here:

import itertools

suits = "DCHS"
ranks = "23456789TJQKA"

cardDeck = list(set(itertools.product(ranks, suits)))

print sorted(cardDeck, key=lambda x: ranks.index(x[0])) 

Gives:

[('2', 'S'), ('2', 'C'), ('2', 'H'), ('2', 'D'), ('3', 'D'), ('3', 'H'), ('3', 'C'), ('3', 'S'), ('4', 'D'), ('4', 'S'), ('4', 'C'), ('4', 'H'), ('5', 'H'), ('5', 'S'), ('5', 'D'), ('5', 'C'), ('6', 'C'), ('6', 'D'), ('6', 'H'), ('6', 'S'), ('7', 'C'), ('7', 'D'), ('7', 'S'), ('7', 'H'), ('8', 'S'), ('8', 'C'), ('8', 'H'), ('8', 'D'), ('9', 'H'), ('9', 'S'), ('9', 'D'), ('9', 'C'), ('T', 'H'), ('T', 'C'), ('T', 'D'), ('T', 'S'), ('J', 'S'), ('J', 'C'), ('J', 'H'), ('J', 'D'), ('Q', 'H'), ('Q', 'C'), ('Q', 'D'), ('Q', 'S'), ('K', 'S'), ('K', 'H'), ('K', 'D'), ('K', 'C'), ('A', 'S'), ('A', 'D'), ('A', 'H'), ('A', 'C')]


Garrett R February 2016

Why not just sort according to the cards rank's index in the ranks string.

For example, an "A" is the 12 element and the "K" is the 11th element. Therefore, all Aces come after Kings.
import itertools

suits = "DCHS"
ranks = "23456789TJQKA"

cardDeck = list(set(itertools.product(ranks, suits)))

print sorted(cardDeck, key = lambda x: ranks.index(x[0]))

Output

[('2', 'S'), ('2', 'C'), ('2', 'H'), ('2', 'D'), ('3', 'D'), ('3', 'H'), ('3', 'C'), ('3', 'S'), ('4', 'D')...

Post Status

Asked in February 2016
Viewed 2,475 times
Voted 11
Answered 3 times

Search




Leave an answer