Python错误:当列表具有多个值时,列表赋值索引超出范围

huangapple go评论105阅读模式
英文:

Python Error: List assignment index out of range when list has more than 1 value

问题

以下是在计算机回合期间发生错误的部分代码:

if computer_calculate == True:
    # ... 其他代码
    for card in computer.hand:
        hand_index += 1
        # ... 其他代码
        for table_card in computer.table:
            table_index += 1
            if played_on == False:
                if (card.value * table_card.value) % 10 == 0:
                    computer.table[table_index] = computer.hand[hand_index]
                    # ... 其他代码
                elif (card.value / table_card.value) % 10 == 0:
                    computer.table[table_index] = computer.hand[hand_index]
                    # ... 其他代码
                elif (card.value + table_card.value) % 10 == 0:
                    computer.table[table_index] = computer.hand[hand_index]
                    # ... 其他代码
                elif (card.value - table_card.value) % 10 == 0:
                    computer.table[table_index] = computer.hand[hand_index]
                    # ... 其他代码
    if card_played == False:
        print("The computer could not find a legal move. The card has been added to its hand.")

请注意,您提供的代码中可能存在一些HTML实体编码,您可能需要将其还原为正常的文本字符,以便代码能够正确运行。此外,如果您需要帮助解决特定的错误或问题,请提供相关的错误消息或更多代码以供参考。

英文:

I am writing code for a card game that I made, and I am trying to add cards to the computer's hand when they can't put one down. The function works completely fine when it has 1 or 0 cards in its hand, but if it has any more, I get Index Error: List assignment index out of range

This is the code that plays during the computer's turn:

def calculate():
    global computer_calculate, player_calculate, table_index, hand_index, deck
    table_index = -1
    hand_index = -1
    card_played = False
    played_on = False
    if computer_calculate == True:
        print("These are the computer's cards.\n" + str(computer.table))
        time.sleep(1)
        print("This is the card it has just drawn.\n" + str(computer.hand[-1]))
        time.sleep(1)
        print("These are all of the cards in its hand.\n" + str(computer.hand))
        time.sleep(1)
        for card in computer.hand:
            hand_index += 1
            card.in_play = False
            for table_card in computer.table:
                table_index += 1
                if played_on == False:
                    if (card.value * table_card.value) % 10 == 0:
                        computer.table[table_index] = computer.hand[hand_index]
                        card_played = True
                        card.in_play = True
                        played_on = True
                        print("The computer played their card. They played " + str(card.value) + " on " + str(table_card.value) + " because " + str(card.value) + " multiplied by " + str(table_card.value) + " equals " + str((card.value * table_card.value)) + ", which is a multiple of ten.")
                        time.sleep(3)
                    elif (card.value / table_card.value) % 10 == 0:
                        computer.table[table_index] = computer.hand[hand_index]
                        card_played = True
                        card.in_play = True
                        played_on = True
                        print("The computer played their card. They played " + str(card.value) + " on " + str(table_card.value) + " because " + str(card.value) + " divided by " + str(table_card.value) + " equals " + str((card.value / table_card.value)) + ", which is a multiple of ten.")
                        time.sleep(5)
                    elif (card.value + table_card.value) % 10 == 0:
                        computer.table[table_index] = computer.hand[hand_index]
                        card_played = True
                        card.in_play = True
                        played_on = True
                        print("The computer played their card. They played " + str(card.value) + " on " + str(table_card.value) + " because " + str(card.value) + " added to " + str(table_card.value) + " equals " + str((card.value + table_card.value)) + ", which is a multiple of ten.")
                        time.sleep(5)
                    elif (card.value - table_card.value) % 10 == 0:
                        computer.table[table_index] = computer.hand[hand_index]
                        card_played = True
                        card.in_play = True
                        played_on = True
                        print("The computer played their card. They played " + str(card.value) + " on " + str(table_card.value) + " because the difference of " + str(card.value) + " and " + str(table_card.value) + " equals " + str(abs(card.value - table_card.value)) + ", which is a multiple of ten.")
                        time.sleep(3)
            if card.in_play == True:
                computer.hand.remove(card)
        if card_played == False:
            print("The computer could not find a legal move. The card has been added to its hand.")

Wherever it says computer.table[table_index] = computer.hand[hand_index], it gives me the error whenever the computer has 2 or more cards in its hand. Otherwise, everything works perfectly fine. If you need the rest of the code just let me know.

答案1

得分: 1

你有两个嵌套的for循环:外部循环遍历计算机手中的卡片,内部循环遍历桌上的卡片。这意味着如果手中有多张卡片,内部for循环必须多次执行。为了使这个过程正常工作,你的table_index变量在内部for循环重新启动之前需要被重置。一种实现这个的方式是将table_index = -1这一行移到外部for循环内,就在hand_index += 1之前。
然而,一个更干净的方法是利用Python的enumerate()函数,正如Nonlinear建议的那样。可以在这里了解更多信息。它允许你遍历一个可迭代对象(比如列表),并在每次迭代时访问索引变量和列表元素,而不需要初始化或增加索引。

英文:

You've got two nested for loops: the outer one iterates through the cards in the computer's hand, and the inner one iterates through cards on the table. This means that the inner for loop has to execute multiple times if there are multiple cards in the hand. In order for this to work properly, your table_index variable needs to get reset before the inner for loop restarts. One way to accomplish this would be to move the line table_index = -1 just inside that outer for loop, right before hand_index += 1.
However, a cleaner way to do this is to make use of Python's enumerate() function, as recommended by Nonlinear. Read about that here.It lets you iterate over an iterable (such as a list) and get access to both the index variable and the list element at each iteration without having to initialize or increment the index.

答案2

得分: -1

你面临的问题是因为在循环中使用 computer.hand 时,你没有初始化 table_index。在第一次迭代中,一切正常(这是计算机有0或1张卡时能够正常工作的原因)。但在第二次迭代中,table_index 保持在之前的任何值上。要解决这个问题,你可以将 table_index = -1 移到第一个 for 循环内部,或者使用 Python 的 enumerate 函数,这将使你的代码更清晰。

英文:

The problem you are facing arises because when looping in computer.hand, you are not initializing table_index. On the first iteration, everything works well (this is the reason it works if the computer has 0 or 1 card). But on the second iteration, table_index stays on whatever value it was before. To solve your problem, you can either move table_index = -1 inside the first for loop, or use the python enumerate function, which would make your code a lot cleaner.

huangapple
  • 本文由 发表于 2023年8月10日 21:24:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876166.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定