使用 python 根据其套件和值对卡片进行排序

Sort cards according to its suite and values using python

有谁能帮我把卡片按套件和vules分类吗? 我有:

list_cards = [('♥', '9'), ('♥', 'J'), ('♦', 'J'), ('♥', '7'), ('♥', '10'), ('♦', '10')]

我需要得到:

[('♥', '7'), ('♥', '9'), ('♥', '10'),('♥', 'J'), ('♦', '10'), ('♦', 'J')]

我试过这样的方法:

return list_cards.sort(key=lambda c: (NAME_TO_VALUE[c[0]], c[1]))
return sorted(list_cards, key=lambda c: (NAME_TO_VALUE[c[0]], c[1]))
return sorted(list_cards)

等等...

但是结果和我想要的不一样。 这是完整的代码:

NOMINALS = ['7', '8', '9', '10', 'J', 'Q', 'K', 'A']
NAME_TO_VALUE = {n: i for i, n in enumerate(NOMINALS)} -> :<class 'dict'>: {'7': 0, '8': 1, '9': 2, '10': 3, 'J': 4, 'Q': 5, 'K': 6, 'A': 7}
list_cards = [('♥', '9'), ('♥', 'J'), ('♦', 'J'), ('♥', '7'), ('♥', '10'), ('♦', '10')]

def sort_hand():
    # return list_cards.sort(key=lambda c: (NAME_TO_VALUE[c[0]], c[1]))
    # return sorted(list_cards, key=lambda c: (NAME_TO_VALUE[c[0]], c[1]))
    return sorted(list_cards)

一种方法是简单地使用辅助函数将卡片与顺序位置相互转换,然后使用这些顺序位置进行排序。

例如:

# These decide sort order, change if different order needed.

suitMap = ['♠', '♣', '♦', '♥']
faceMap = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

def cardToOrd(cardVal):
    return 13 * suitMap.index(cardVal[0]) + faceMap.index(cardVal[1])

def ordToCard(ordVal):
    return (suitMap[ordVal // 13], faceMap[ordVal % 13])

def sortCards(cardList):
    newList = [cardToOrd(i) for i in cardList]
    newList.sort()
    return [ordToCard(i) for i in newList]

cards = [('♥', '9'), ('♥', 'J'), ('♦', 'J'), ('♥', '7'), ('♥', '10'), ('♦', '10')]
print(cards)
print(sortCards(cards))

如果有可能使用无效卡片,您可以让它更健壮一些。如下更改序数转换函数将强制无效卡到 ('?', '?') 并将它们放在末尾:

def cardToOrd(cardVal):
    try:
        return 13 * suitMap.index(cardVal[0]) + faceMap.index(cardVal[1])
    except:
        return 99999

def ordToCard(ordVal):
    try:
        return (suitMap[ordVal // 13], faceMap[ordVal % 13])
    except:
        return ('?', '?')

顺便说一句,这可能是我放入 class(例如,cardsetdeck)的内容,因此我可以将所有卡片处理代码收集到一个单一连贯的对象。我将把它留作 reader 的练习:-)

也许你可以创建几个字典来存储你想要的花色和等级的顺序,假设你知道这些牌是有效的:

SUITS = ['♥', '♦', '♠', '♣']
RANKS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
SUIT_ORDER = {suit: order for order, suit in enumerate(SUITS)}
RANK_ORDER = {rank: order for order, rank in enumerate(RANKS)}

list_cards = [('♥', '9'), ('♥', 'J'), ('♦', 'J'), ('♥', '7'), ('♥', '10'), ('♦', '10'), ('♠', '6'), ('♣', 'A')]
sorted_list_cards = sorted(list_cards, key=lambda c: (SUIT_ORDER[c[0]], RANK_ORDER[c[1]]))
print(sorted_list_cards)

输出:

[('♥', '7'), ('♥', '9'), ('♥', '10'), ('♥', 'J'), ('♦', '10'), ('♦', 'J'), ('♣', 'A'), ('♠', '6')]