【问题标题】:Python -- How is my list out of range?Python——我的列表怎么超出范围?
【发布时间】:2015-07-30 21:29:06
【问题描述】:

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

谁能告诉我我的列表是如何超出范围的?

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

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

【问题讨论】:

  • 错误在哪一行?
  • 我们需要比这更多的细节。什么线?你试过什么?有哪些例子?
  • 你能粘贴错误的回溯吗?
  • 我假设您在读取文件时遇到了错误。您能否提供文件cs7Assn7.txt 中出现错误的行/行?
  • func_read 中,您假设您的4 个字段由+ 分隔,但在func_order 中,您没有在字段之间写入+。这 4 个字段根本没有被任何字符分隔。两个字符串之间的+ 只是将它们连接起来,并且not 在字符串之间添加+ 字符

标签: python list arraylist range outofrangeexception


【解决方案1】:

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

widgetsNum=places[1]
gidgetsNum=places[2]
doodadsNum=places[3]

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

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 2020-04-04
    • 2015-03-03
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多