You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现21点手牌计数函数出现列表索引越界问题求助

解决21点手牌计数函数的索引越界问题

你的count_total函数是索引越界的根源:

  • 当你用for card in total_cards遍历手牌列表时,card拿到的是手牌的点数值(比如11、10、2这类),但你却写了total += total_cards[card]——这相当于把点数数值当成列表索引来用。比如拿到点数11时,你的手牌列表长度肯定小于11,自然触发索引越界错误。
  • 就算改成for card in range(0, len(total_cards)),如果没把取值逻辑改对,错误依然存在。

修正后的count_total函数可以选两种写法:

  1. 直接遍历元素累加(最简洁):
def count_total(total_cards):
    total = 0
    for card in total_cards:
        total += card  # 直接累加手牌点数本身
    return total
  1. 通过索引遍历累加:
def count_total(total_cards):
    total = 0
    for idx in range(len(total_cards)):
        total += total_cards[idx]  # 用索引取对应手牌点数
    return total

另外提个小细节:输入提示里的Typr是拼写错误,应该改成Type。

内容的提问来源于stack exchange,提问作者Niccolò Baresani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:16:13