繁体   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