Python - 我的列表如何超出范围?

时间:2015-05-19 07:18:04

标签: python list arraylist range outofrangeexception

分配是让用户选择读取数据文件或写入数据文件。我想出了如何写它但我无法理解我当前的错误:我的列表超出了范围。

有人可以告诉我我的名单是如何超出范围的吗?

我相信,我做的一切都是正确的,但我老实说不确定我的名单是如何超出范围的。请帮帮我们。谢谢!

#Run again

useAgain=bool(True)

while useAgain:

#Display Options
    print("\nYou may either read or write to the file:\n"\
          "\n'1' - To read and display records in the data file."\
          "\n'2' - To order.\n")

    choice=str(input("Please enter your choice here: "))


    def func_read():
        cs7Assn7=open("cs7Assn7.txt",'r')
        line=cs7Assn7.readline()
        places=line.split('+')
        userID=places[0]
        widgetsNum=places[1]
        gidgetsNum=places[2]
        doodadsNum=places[3]
        print("Customer ID: ",userID,"\nNumber of Widgets: ",widgetsNum,\
              "\nNumber of Gidgets: ",gidgetsNum,"\nNumber of Doodads: ",\
              doodadsNum,"\n")

    def func_order():
        userID=str(input("Please enter your user ID(2 letters"\
                         " followed by 3 numbers: "))
        widgetsNum=abs(int(input("Number of Widgets you would"\
                                   " like to order: ")))
        gidgetsNum=abs(int(input("Number of Gidgets you would"\
                                   " like to order: ")))
        doodadsNum=abs(int(input("Number of Doodads you would"\
                                   " like to order: ")))

        items=open("cs7Assn7.txt",'a')
        items.write(str(userID) + str(abs(widgetsNum)) + str(abs(gidgetsNum))\
                    + str(abs(doodadsNum)) + '\n')
        items.close()

    if choice=="1":
        func_read()
    elif choice=="2":
        func_order()
    useAgain=str(input("\nWould you like to run this code again? Type 'Y' to"\
                       " run or 'N' to stop: "))
    useAgain=useAgain.lower()
    if useAgain !="y":
        useAgain=bool(False)

1 个答案:

答案 0 :(得分:0)

我猜,你在以下任何一行都会收到错误:

def parse_info():
 info = open("info.txt", "r")
 max_age = 0
 max_name = ''
 min_age = float('inf')
 min_name = ''

 for line in info:
    m_list = line.split(" ")
    if int(m_list[1]) > max_age:
        max_age = int(m_list[1])
        max_name = m_list[0]
    elif int(m_list[1]) < min_age:
        min_age = int(m_list[1])
        min_name = m_list[0]
 info.close()
 return ((min_name,min_age),(max_name,max_age))
 #end of function
nameAge=parse_info()
f = open("output.txt","w")
f.write(nameAge[0][0]+" "+str(nameAge[0][1])+"\n")
f.write(nameAge[1][0]+" "+str(nameAge[1][1]))

原因是文本文件中的某些行没有三个“+”符号。 因此,在拆分时,您没有4个项目的列表。因此,错误。