Python - sorting a list of tuples by an uneven list
Question: 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?


Answer: 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](https://ideone.com/nEHa0Q):

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

