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

Python列表删除元素触发IndexError:索引越界问题排查与修复

解决Python中的IndexError: list index out of range问题

先看一下你提供的代码和报错信息:

你的代码:

dosya=open("a.txt","r").read()
dosya=dosya.split(" ")
uzun=len(dosya)
sayac=[0 for i in range(len(dosya))]
for i in range(uzun):
    for j in range(i+1,uzun):
        if(dosya[i]==dosya[j]):
            del dosya[j]
            sayac[i]+=1
    sayac[i]+=1
    del dosya[i]
    i+=1
print sayac

报错信息:

Error : IndexError: list index out of range

错误原因分析

这个问题的核心是你在遍历列表的同时直接修改了列表长度,导致循环索引和实际列表的长度完全不匹配:

  1. 循环范围固定但列表动态缩短:你一开始用uzun = len(dosya)获取了列表的初始长度,所有循环都基于这个固定值运行。但在循环过程中,你不断用del dosya[j]和del dosya[i]删除元素,列表的实际长度会越来越短。当循环到后面的索引时,这个索引已经超出了当前列表的实际长度,自然触发了IndexError。
  2. 手动修改循环变量打乱逻辑:Python的for循环是自动迭代range(uzun)生成的序列的,你在循环里手动执行i+=1会彻底打乱原本的迭代顺序,让后续的索引操作完全偏离预期。
  3. 统计列表与原列表索引失配:每次删除dosya的元素后,sayac的长度并没有同步调整,后续的sayac[i]操作会因为原列表元素的缺失而对应错误的统计项,进一步放大问题。

修复方案

你的需求本质是统计文本中每个单词的出现次数,用字典实现会更简洁高效,完全避开索引问题:

方案1:用字典统计词频(推荐)

这种方法不需要修改原列表,直接遍历统计,逻辑清晰且性能更好:

# 用with语句自动管理文件,避免忘记关闭文件
with open("a.txt", "r") as f:
    file_content = f.read()

words = file_content.split(" ")
word_count = {}

for word in words:
    # 处理split后可能出现的空字符串(比如文本中有多个连续空格)
    cleaned_word = word.strip()
    if not cleaned_word:
        continue
    # 统计次数
    if cleaned_word in word_count:
        word_count[cleaned_word] += 1
    else:
        word_count[cleaned_word] = 1

# 输出完整的单词-次数映射
print(word_count)
# 如果只需要次数列表,和你原来的sayac格式一致
print(list(word_count.values()))

方案2:坚持用列表处理(不推荐,效率较低)

如果你一定要用类似原代码的列表思路,不要直接修改原列表,而是创建新列表来保存唯一单词,同时同步统计次数:

with open("a.txt", "r") as f:
    file_content = f.read()

words = file_content.split(" ")
unique_words = []
sayac = []

for word in words:
    cleaned_word = word.strip()
    if not cleaned_word:
        continue
    if cleaned_word in unique_words:
        # 找到对应单词的索引并增加计数
        index = unique_words.index(cleaned_word)
        sayac[index] += 1
    else:
        unique_words.append(cleaned_word)
        sayac.append(1)

print(sayac)

内容的提问来源于stack exchange,提问作者Recep Gümüş

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:47:18