1

在我的 Rummy 程序中,我必须对输出进行排序,以便卡片以从高到低的值打印(K 是最高的,A 是最低的),例如:

输入:1. 8H、8C、8S、2C、7S、9H、KD

输出:1. 8S、8H、8C、KD、9C、7H、2C

run4 = []
set4 = []
run3 = []
set3 = []
other = []
cards = input('1. ')
cards = cards.split(', ')
card_numbers_count = {'A':0, '2':0, '3':0, '4':0, '5':0, '6':0, '7':0, '8':0, '9':0, 'T':0, 'J':0, 'Q':0, 'K':0}
card_suit_count = {'H':0, 'D':0, 'S':0, 'C':0}

def card_suit_key(card):
    suit_vals = {'S': 1, 'H': 2, 'C': 3, 'D': 4}
    return suit_vals[card[1]]
def numerical_order(card):
    num_vals = {'K': 1, 'Q': 2, 'J': 3, 'T': 4, '9': 5, '8': 6, '7': 7, '6': 8, '5': 9, '4': 10, '3': 11, '2': 12, 'A': 13}
    return num_vals[card[1]]

# card value
for card in cards:
    card_number = card[:-1]
    card_numbers_count[card_number] += 1
for card in cards:
    card_number = card[:-1]
    if card_numbers_count[card_number] == 3:
        run3.append(card)
        run3.sort(key=card_suit_key)
    elif card_numbers_count[card_number] == 4:
        run4.append(card)
        run4.sort(key=card_suit_key)
    elif card_numbers_count[card_number] > 3 or card_numbers_count[card_number] < 3:
        other.append(card)
        print (other)
        #other.sort(key=numerical_order)
print (run4, run3, other)

# card suit
for card in cards:
    card_suit  = card[1:]
    card_suit_count[card_suit] += 1
for card in cards:
    card_suit  = card[1:]

我已经编辑了这个问题,因为我能够做到从最高到最低订购西装,但我不能对卡值做同样的事情。任何帮助,将不胜感激。谢谢。

4

3 回答 3

2

通过一个简单的查找表进行排序将相当快,如果您创建该表的数据驱动,如下所示,整个事情将很容易在必要时更改 - 只需重新排序RANKS和/或中的值SUITS根据需要列出。

from itertools import product

RANKS = 'A 2 3 4 5 6 7 8 9 10 J Q K'.split()  # low to high value
SUITS = 'S H C D'.split()  # high to low suit
DECK = list(''.join(it) for it in product(RANKS, SUITS))
LUT = dict((card, index) for index,card in enumerate(DECK))

hand = ['8H', '8C', '8S', '9C', '7S', '9H', 'KD']
print sorted(hand, key=LUT.get)

输出:

['7S', '8S', '8H', '8C', '9H', '9C', 'KD']
于 2013-04-07T18:46:29.347 回答
2

我不太确定您是如何对示例进行排序的,但是如果您想按花色(黑桃、红心、梅花、方块)对卡片进行排序,您可以创建自定义键功能。您可以像这样在字典中保存每件西装的“重量”:

编辑:这是一个简化版本,通过在键函数中返回一个元组,可以同时进行两种排序:

>>> cards = ['8H', '8C', '8S', '2C', '7S', '9H', 'KD']
>>>
>>> def card_suit_key(card):
...     suits = 'S H C D'.split()
...     ranks = 'K Q J 10 9 8 7 6 5 4 3 2 A'.split()
...     return (suits.index(card[-1]), ranks.index(card[:-1]))
...
>>> cards.sort(key=card_suit_key)
>>> cards
['8S', '7S', '9H', '8H', '8C', '2C', 'KD']
于 2013-04-07T17:50:42.813 回答
1

以正确的顺序将其存储在临时数组/列表中,然后将其复制回原始数组/列表。

于 2013-04-07T17:57:59.560 回答