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

Python for Everybody练习10.2报IndexError索引越界问题求助

《Python for Everybody》10.2节练习索引越界报错修复

报错信息

Traceback (most recent call last):
  File "C:\Users\tinyp\Desktop\py4e\new.py", line 10, in <module> 
    words = words[5].split(":")
IndexError: list index out of range

错误根因

  • 行筛选逻辑错误:使用line.startswith("From")作为判断条件时,会同时匹配目标行(From 开头,后接邮箱地址)和mbox文件中大量From:开头的元信息行,后者按空格分割后元素数量不足6个,访问索引为5的元素时就会触发索引越界。
  • 小时统计逻辑错误:提取到小时字符串后错误使用for循环遍历字符串,会把两位的小时值拆分为单个字符计数,统计结果完全错误。
  • 排序逻辑错误:最终存储元组为(计数值, 小时)且开启倒序排列,不符合题目要求的按小时升序输出的规则。

修复后完整代码

name = input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
    line = line.rstrip()
    # 修正筛选条件:From后加空格,仅匹配发件人记录行
    if not line.startswith("From "):
        continue
    words = line.split()
    time_seg = words[5].split(":")
    hour = time_seg[0]
    # 直接对小时值计数,不遍历字符串
    counts[hour] = counts.get(hour, 0) + 1
# 按小时升序排序
hour_list = sorted(counts.items())
# 逐行输出结果
for h, c in hour_list:
    print(h, c)

关键修改说明

  • 行判断条件修改为line.startswith("From "),过滤掉格式不符合的From:开头行,保证所有进入后续处理的行分割后都有至少7个元素,访问索引5不会越界
  • 删除了对小时字符串的错误遍历逻辑,直接以提取到的小时字符串为key更新计数字典
  • 调整排序逻辑,直接对计数字典的键值对按小时key做升序排列,符合题目输出要求

内容的提问来源于stack exchange,提问作者Sae

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:45:59