python-3.x 无法确定列表索引超出范围的原因

w1jd8yoj  于 2022-11-19  发布在  Python
关注(0)|答案(3)|浏览(149)

我创建了一个函数来计算一个21点的值与一个循环,但它一直告诉我,指数是超出范围,我不能找出原因
我试着从“for card in total_cards”切换到“for card in range(0,len(total_cards))”,希望这样能解决我的问题,但是我总是得到同样的错误。既然这两个错误似乎都源于函数,那么我在这里遗漏了什么呢?提前感谢大家。

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
gcxthw6b

gcxthw6b1#

这就是问题所在:

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

你不需要在集合中建立索引--for循环已经为你做了。只需将它改为:

for card in total_cards:
    total += card
hk8txs48

hk8txs482#

我是一个新手,但我相信当你在python中使用for循环遍历一个列表时,你已经从列表中“拉”出了数据。

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

应为:

for card in total_cards:
    total += card
brjng4g3

brjng4g33#

player_cards包含从0到len的值在第一次调用count_total时,player_cards具有3个元素,一个来自for循环i==2和i==4,另一个来自调用的上一行。在count_total中使用“for card in total_cards”,意思是卡片取total_cards的值,即player_cards。然后尝试从长度为3的列表中检索元素,索引为“card”=从0到12的值。
如果您的使用范围需要从上限减去1:对于范围(0,len(total_cards)-1)内卡片

相关问题