Python: 列表赋值超出范围

0 投票
6 回答
2055 浏览
提问于 2025-04-15 20:18

这个模块是我用Python做的一个简单待办事项应用的一部分...

def deleteitem():
             showlist()
             get_item = int(raw_input( "\n Enter number of item to delete: \n"))
             f = open('todo.txt')
             lines = f.readlines()
             f.close()
             lines[get_item] = ""
             f = open('todo.txt','w')
             f.writelines(lines)
             f.close()
             showlist()

当往列表里添加项目时,f中的行数显然会变化... 这里的问题是,比如说用户输入了'10',而文件里只有9行(或者输入了其他不在范围内的数字),程序就会按预期退出,显示:

IndexError: list assignment index out of range

我可以在这个模块里加些什么,让用户输入一个在范围内的项目呢?我在想可能需要用到一个Try块...或者有没有办法捕捉到异常...我觉得应该有简单的方法可以做到这一点...

6 个回答

3

要么在访问列表的某个位置时捕捉到IndexError错误,要么提前检查一下列表的长度,看看能不能安全地访问那个位置。

3

首先读取文件,然后在一个循环中询问用户,直到得到一个可以接受的答案:

while True:
    get_item = int(raw_input( "\n Enter number of item to delete: \n"))
    if get_item >=0 and get_item < len(lines):
        break

当然,如果文件是空的,这样做就会出错,而且也没有给用户提供任何关于可接受值的提示。不过,这里留给你一些练习。

1

对你当前代码的合理修改:

def deleteitem():
  showlist()

  with open("todo.txt") as f:
    lines = f.readlines()
  if len(lines) == 0:  # completely empty file
    return  # handle appropriately
  prompt = "Enter number to delete (1-%d), or 0 to abort: " % len(lines)
  while True:
    input = raw_input(prompt)
    try:
      input = int(input, 10)
    except ValueError:
      print "Invalid input."
    else:
      if 0 <= input <= len(lines):
        break
      print "Input out of range."
  if input == 0:
    return
  input -= 1  # adjust from [1,len] to [0,len)

  #del lines[input]  # if you want to remove that line completely
  lines[input] = "\n"  # or just make that line blank (what you had)

  with open("todo.txt", "w") as f:
    f.writelines(lines)

  showlist()

撰写回答