简体   繁体   English

Python:列表分配超出范围

[英]Python: list assignment out of range

This module is part of a simple todo app I made with Python... 这个模块是我用Python制作的一个简单的todo应用程序的一部分...

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()

The number of lines in f obviously changes as items are added to the list... Problem here is that for example if a user enters '10' when there are only 9 lines in the file ( or anything else not in range) , it exits as expected with : f中的行数显然会随着项目添加到列表而发生变化……这里的问题是,例如,如果用户在文件中只有9行(或其他不在范围内的行)时输入“ 10”,则会按预期退出:

IndexError: list assignment index out of range

What can I add to the module so as to have it prompt user to enter an item within the range? 我可以在模块中添加什么以便提示用户输入范围内的项目? I am assuming maybe a Try block ... Or is there a way to catch an exception.. I am guessing there is an easy way to do this... 我假设也许是一个Try块...还是有一种捕获异常的方法..我猜有一个简单的方法可以做到这一点...

在建立索引时捕获IndexError或预先检查列表的len()

First read the file, and then ask user in a loop, until the answer is acceptable: 首先阅读文件,然后循环询问用户,直到答案可以接受为止:

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

That will, of course, break when the file is empty and doesn't give any hint about the acceptable values to the user. 当然,这将在文件为空时中断,并且不会向用户提供任何有关可接受值的提示。 But let's keep some exercise for you. 但是,让我们为您做些运动。

Judicious changes to your current code: 明智地更改您当前的代码:

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()
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()
             try:
                 lines[get_item] = ""
             except Exception,err: 
                 print err
             f = open('todo.txt','w')
             f.writelines(lines)
             f.close()
             showlist()

Try something like this: 尝试这样的事情:

def deleteitem():

showlist()
f = open('todo.txt')
lines = f.readlines()
f.close()
if len(lines) == 0:
    print "File is empty!"
    return False
print "File has %d items\n" % len(lines)
item = 0
while item < len(lines):
    item = raw_input( "\n Enter number of item to delete(0-%d): \n" % len(lines))
    item = int(item) # because of the width of the code
f = open('todo.txt','w')
f.write(lines[0:item-1])
f.write(lines[item::])
f.close()
showlist()

For what it's worth.... I'll put the code to my todo.py program here... It's just something I run from a Terminal in OS X to keep control of stuff I need to do at work...I am sure it's horribly un-pythonic,inefficient and everything else...but maybe it'll be of use to some one who stumbles across this thread : 为了它的价值。...我将代码放在这里的todo.py程序中...这只是我在OS X的Terminal中运行的内容,以控制我在工作中需要做的事情...我确保这是可怕的非Python的,低效的以及其他所有内容...但是对于偶然发现此线程的某个人来说,它可能会有用:

from __future__ import with_statement
import sys
import os
import fileinput

os.system('clear')

print ("##############          TO DO LIST       ############")
print ("##############                           ############")

def showlist():
    os.system('clear')
    print ("############  Current To Do List  ######")
    print ("########################################")

    get_list = open('todo.txt')
    entire_list = get_list.readlines()
    for i in range (len(entire_list)):
        print i, entire_list[i]
    get_list.close()
    print ("########################################")
    print ("########################################")

def appendlist():
    print ("#######################################")
    print ("#######################################")


    addtolist = str( raw_input("Enter new item:  \n"))
    thelist = open('todo.txt', 'a')
    thelist.write(str(addtolist))
    thelist.write(str('\n'))
    thelist.close()  
    showlist()


def deleteitem():
    showlist()

        with open("todo.txt") as f:
            lines = f.readlines()
            if len(lines) == 0:  
                return  
        prompt = "Enter number to delete or '0' to abort: " 
        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

        lines[input] = "" 

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

        showlist()

while True:

    askme = raw_input("\nDo you want to:\n(S)ee list\n(A)ppend list\n(D)elte from list\n(Q)Quit?\n")
    print str('\n')

    if askme == "S":
        showlist()
    elif askme == "A":
        appendlist()
    elif askme == "D":
        deleteitem()

    elif askme == "Q":
        sys.exit()
    else: 
        print ("Try again?")

print ("#######################################")
print ("#######################################")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM