Python:索引超出范围,但我不明白为什么

时间:2018-01-15 16:03:29

标签: indexing

我正在尝试编写一个打开文件的程序,创建一个包含该文件每一行的列表,并从该列表中删除一些单词。我有一个Index Out of Range错误。

#! /usr/bin/python3

# open the file
f = open("test.txt", "r")
# a list that contains each line of my file (without \n)
lines = f.read().splitlines()
# close the file
f.close()

# some words I want to delete from the file
data = ["fire", "water"]

# for each line of the file...
for i in range(len(lines)):
    # if this line is in [data]
    if lines[i] in data:
        # delete this line from [data]
        print(lines[i])
        del lines[i]

这是我的文字档案:

sun
moon
*
fire
water
*
metal

这是我的输出:

fire
Traceback (most recent call last):
  File "debug.py", line 16, in <module>
    if lines[i] in data:
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

我将首先解决索引错误。 在你的第一篇文章中发生的事情是它需要列表的长度 这是7,所以len(行)= 7将导致范围(7)=(0,7),这将做到这一点:

  • lines [0] = sun
  • lines [1] = moon
  • lines [2] = *
  • lines [3] = fire
  • lines [4] = water
  • lines [5] = *
  • lines [6] = metal

=&GT;

  • lines [0] = sun
  • lines [1] = moon
  • lines [2] = *
  • 已删除行[3] = fire
  • lines [3] = water
  • lines [4] = *
  • lines [5] = metal

如果你现在删除行[3],它仍然会尝试迭代行[6],虽然它不再存在。

它还将继续迭代下一个索引线[4],因此永远不会检查水,它会被吸收。

我希望这会有所帮助,我建议你这样做:

# open the file
f = open("test.txt", "r")
# a list that contains each line of my file (without \n)
lines = f.read().splitlines()
# close the file
f.close()

# some words I want to delete from the file
data = ["fire", "water"]


for i in data:
    if i in lines:
        lines.remove(i)

print(lines)

输出: ['sun','moon','','','metal']