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



有人能帮我按套数和价值对卡片进行排序吗?我有:

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 ('?', '?')

顺便说一句,这可能是我放在一个类中的东西(例如,cardsetdeck(,所以我可以将所有卡处理代码收集到一个连贯的对象中。我将把它留给读者练习:-(

假设你知道卡片是有效的,也许你可以创建几个字典来存储你想要的套装和等级的顺序:

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

相关内容

  • 没有找到相关文章

最新更新