我试图用代码ih在python3中按等级和套装对一手牌进行排序

2024-10-04 05:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经概述了我在代码中遇到问题的地方。我是一个python新手,需要一些帮助。我想做的是处理一手牌,然后使用选择排序按西装和等级排序。我希望给每张卡片分配自己的值,然后比较卡片,最终完成分类。目前,当我运行代码时,我得到一个错误,指出我的字符串索引超出范围。我假设这是因为我没有正确定义card1 card2索引,但我不确定如何修复它们。提前谢谢!
编辑:对于card1和card2,我希望能够根据它们的等级进行比较,如果我得到一个正数,我知道card1大于card2,如果是负数,我知道card1小于card2。然后我可以在find_ngubiggest中使用它来比较13张牌。在

import random

def shuffle_deck():
    result = []
    for suit in ['H', 'C', 'D', 'S']:
        for value in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']:
            result += [value + suit];
    random.shuffle(result)
    return result

def deal_hand(n, deck):
    hand = []
    for i in range(n):
        card = deck.pop()
        hand += [card]
    return hand

# This is where the trouble I'm having begins as I'm not sure what cards to compare
def compare(card1,card2):
    value = 'A23456789TJQK'
    suit = 'HCDS'
    card1 = value.find(card1[0] [0]) + ((suit.find(card1[0][1]))*20)
    card2 = value.find(card2[1] [0]) + ((suit.find(card2[1][1]))*20)
    return(card1 - card2)

def find_largest(hand, n):
    largestIdx = 0
    for i in range(1, n):
# I am also not certain what should be compared in this part. I know it should be the 
#current hand compared to the position of the largest card currently.
        if compare(hand [i], hand[largestIdx]) > 0:
            largestIdx = i
    return largestIdx

def selection_sort(hand):
    for idx in range(len(hand)-1, 0, -1):
        largestIdx = find_largest(hand, idx +1)
        hand[idx], hand[largestIdx] = hand[largestIdx], hand[idx]
    print(hand)

编辑:

^{pr2}$

Tags: theinforreturnvaluedefresultfind
1条回答
网友
1楼 · 发布于 2024-10-04 05:28:22

如果我正确地遵循了您的代码,变量card1和{}应该包含一些字符串,比如'AC'或{}。看起来您想分别查看西装和号码(value.find(card1[0] [0]) + ((suit.find(card1[0][1]))*20))。这里只需要一个索引,而不是两个。查看以下示例:

>>> a = 'AC'
>>> a[0]
'A'
>>> a[1]
'C'
>>> a[0][0]
'A'
>>> a[0][1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

字符串'C'只有一个元素,因此当您执行card1[0][1]时,会出现索引错误。你想用

^{pr2}$

这应该可以消除你的IndexError。在

相关问题 更多 >