排序算法:使用排序函数将 python 3 中的元组与整数进行比较

Sort algorithm: Comparing tuple to integer in python 3 with sort function

下面的扑克手牌评估器正在生成玩家所持不同牌的排名。它在 Python 2 中运行良好,但在 python 3 中不起作用,因为排序函数无法再将元组与整数进行比较。我怎样才能使它在 python 3 中的行为方式与它在 python 2 中的行为方式相同?

排序需要决定哪些卡片最好:

(1, (11, 8, 7, 6, 2)) # high card 11 (rank5)
(1, (12, 11, 8, 7, 2)) # high card 12 (rank4)
((3, 2), (11, 12))  # full house (triple and pair) (rank1)
((2, 1, 1, 1), (12, 11, 7, 6)) # pair of 12 (rank3)
((3, 1, 1), (12, 6, 3)) # three of 12 (rank2)

如果将整数与元组进行比较,则元组的第一项应该是相关的。 python 2 中的排序函数会正确地对上述内容进行排序,但在 python 3 中我收到一条错误消息,整数无法与元组进行比较。

我需要如何调整按键功能?

def keyfunction(x):
    v= x[1]
    return v


def poker(hands):
    scores = [(i, score(hand.split())) for i, hand in enumerate(hands)]
    #print (scores)
    winner = sorted(scores , key=keyfunction)[-1][0]
    return hands[winner]

def score(hand):
    ranks = '23456789TJQKA'
    rcounts = {ranks.find(r): ''.join(hand).count(r) for r, _ in hand}.items()
    #print (rcounts)
    score, ranks = zip(*sorted((cnt, rank) for rank, cnt in rcounts)[::-1])
    if len(score) == 5:
        if ranks[0:2] == (12, 3): #adjust if 5 high straight
            ranks = (3, 2, 1, 0, -1)
        straight = ranks[0] - ranks[4] == 4
        flush = len({suit for _, suit in hand}) == 1
        '''no pair, straight, flush, or straight flush'''
        score = ([1, (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
    return score, ranks

poker(['8C TS KC 9H 4S','AC TS KC 9H 4S', 'AD AS KD KS KC', '9C AD KD AC 8C', 'AC 5H 8D AD AS'])

分配score时,您可以简单地将指示大牌的整数转换为单元素元组。

...
score = ([(1, ), (3,1,1,1)], [(3,1,1,2), (5,)])[flush][straight]
...