TheMuffinMan834
TheMuffinMan834

Reputation: 27

Way of using sorted function in a different manner?

I am creating a game of poker using python3 and for sorting the hands i am doing it like this :

C < D < H < S and 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < T < J < Q < K < A.

The output looks like this:

Sorted Hand: ['D5', 'DA', 'DT', 'HA', 'SQ']

But I need it to look like:

Sorted Hand: ['D5', 'DT', 'DA', 'HA', 'SQ'].

I am using the sorted function to do this, is there any way to customize the way the sorted function works and make it so it isn't taking the letters alphabetically but numerically? I'm at a loss here... =/

Upvotes: 0

Views: 61

Answers (2)

John
John

Reputation: 13699

Just a variant of what @thefourtheye already posted

def customSort(card):

    suit, value = card
    value_lookup = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}

    return value_lookup.get(value, int(value))

print sorted(['D5', 'DA', 'DT', 'HA', 'SQ'], key=customSort)

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239453

k1, k2 = ['C','D','H','S'], ['2','3','4','5','6','7','8','9','T','J','Q','K','A']
data = ['D5','DA','DT','HA','SQ']
print sorted(data, key=lambda x: k1.index(x[0]) * 13 + k2.index(x[1]))

Output

['D5', 'DT', 'DA', 'HA', 'SQ']

Upvotes: 2

Related Questions