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

标签 python sorting playing-cards

有人可以帮我按套件和值(value)对卡片进行排序吗? 我有:

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),因此我可以将所有卡片处理代码收集到一个单个连贯的物体。我将把它作为练习留给读者:-)

关于python - 使用 python 根据卡片的套件和值对卡片进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65586641/

相关文章:

python - 出现运行时错误 : unsupported value when trying to insert binary data into a blob field in a sqlite3 table using python

algorithm - 排序一副纸牌

java - Arrays.sort() -- 原始和复杂数据类型的两种不同排序策略

Java 扑克牌游戏框架

c# 将数组列表复制到数组

python - 继续获取 CORS 策略 : No 'Access-Control-Allow-Origin' even with FastAPI CORSMiddleware

python - 将 groupby-apply 结果分配给父数据框

Python self[name] = value 是什么意思?

C++ 基于其他 int 数组排序

python - Pandas 列在一个组内排序,忽略其他列