簡體   English   中英

無法弄清楚為什么我的列表索引超出范圍

[英]Can't figure out why my list index is out of range

我創建了一個 function 來計算帶有 for 循環的二十一點牌的價值,但它一直告訴我索引超出范圍,我不知道為什么

我嘗試從“for card in total_cards”切換到“for card in range(0, len(total_cards))”希望這能解決我的問題,但我一直遇到同樣的錯誤。 由於這兩個錯誤似乎都源自 function,我在這里缺少什么? 謝謝大家。

import random

def count_total(total_cards):
    total = 0
    for card in total_cards:
        total += total_cards[card]
    return total


cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

house_cards = []
player_cards = []
for i in range (1, 5):
    if i % 2 == 0:
        player_cards.append(cards[random.randint(0, len(cards) - 1)])
    elif i % 2 != 0:
        house_cards.append(cards[random.randint(0, len(cards) - 1)])

print(house_cards)
print(player_cards)

should_continue = True
while should_continue:
    action = input("Typr 'y' to ask for a card or 'n' to stop: ")
    if action == "n":
        should_continue = False
        break
    elif action == "y":
        player_cards.append(cards[random.randint(0, len(cards) - 1)])
        count_total(player_cards)
        if count_total(player_cards) > 21:
            should_continue = False
            print("You have gone over 21, you lost!")
            break

這就是問題:

for card in total_cards:
    total += total_cards[card]

您不需要索引到集合中 - for循環會為您做這件事。 只需將其更改為:

for card in total_cards:
    total += card

我比較新,但我相信當您使用 for 循環遍歷 python 中的列表時,您已經從中“提取”了數據。 所以:

for card in total_cards:
    total += total_cards[card]

應該:

for card in total_cards:
    total += card

player_cards 包含從 0 到 len(cards)-1=12 的值。 在第一次調用 count_total 時,player_cards 有 3 個元素,一個來自 for-loop i==2 和 i==4,一個來自調用上面的行。 在 count_total 中,您使用“for card in total_cards”,這意味着該卡片采用 total_cards 的值,即 player_cards。 然后您嘗試從長度為 3 且索引“card”= 值從 0 到 12 的列表中檢索元素。

如果您使用范圍,則需要從上限中減去 1:for card in range(0, len(total_cards)-1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM