gpt4 book ai didi

Python:如何编辑数组中元素的顺序?

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:28 25 4
gpt4 key购买 nike

在我的 Rummy 程序中,我必须对输出进行排序,以便按从高到低的值(value)打印卡片(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:]

我已经编辑了这个问题,因为我能够按照从最高到最低的顺序排列花色,但我不能对卡片值(value)做同样的事情。任何帮助,将不胜感激。谢谢。

最佳答案

通过一个简单的查找表排序会相当快,如果您创建该表是数据驱动的,如下所示,必要时整个事情将很容易改变——只需重新排序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']

关于Python:如何编辑数组中元素的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15864978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com