使用拆分方法时,列表索引超出范围错误

2024-09-28 20:48:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在给一家书店编码,正在检查是否一切正常。我目前正在为员工创建一种方法,将书籍添加到写入文件的内置书籍目录中,并尝试使用拆分方法显示信息。在Inventory类中测试add_book方法时,它会打印第一本书的信息,然后给出一个列表索引超出范围的错误。如果可能的话,请帮忙。这是守则-

#This program is a shopping cart for ABC book store
#Created by Aykhan Salimov on 09.22.2020
#This is a class for books
class Book:
    def __init__(self, number, title, author, genre, price):
        self.number = number
        self.title = title
        self.author = author
        self.genre = genre
        self.price = price
    def __str__(self):
        return "This book's name is " + self.title + "\n" + "This book's author is " + self.author + "\n" + "This book's genre is " + self.genre + "\n" + "This book's price is " + self.price
#This is a class for the inventory of books for sale
class Inventory:
    def __init__(self, make):
        self.make = make
    def add_book(self):
        with open('booklist.txt') as f:
            x = f.read().splitlines()
            Content = f.read()
        Counter = 0 
        CoList = Content.split("\n") 
        for i in CoList: 
            if i: 
                Counter += 1
        loop = True
        y = 0
        print("Current Books: ")
        print("====================================================")
        while(loop):
            myLine = x[y]
            print(myLine)
            myContent = ""
            spliter = myLine.split("\n")
            myContent[spliter[1]] = spliter[2]
            y = y + 1
            if y == counter:
                loop = False
        f.close()
        print(myContent)
        print("====================================================")
        print("Please specify the book information for the book you wish to add")
        addbookn = input("Please input the number of the book you wish to add: ")
        addbookt = input("Please input the title of the book you wish to add: ")
        addbooka = input("Please input the author of the book you wish to add: ")
        addbookg = input("Please input the genre of the book you wish to add: ")
        addbookp = input("Please input the price of the book you wish to add: ")
        newBook = Book(addbookn, addbookt, addbooka, addbookg, addbookp)
        f.open = open("booklist.txt", "a")
        f.append("/n%s" % (newBook))
    def display(self):
        print("===========================================")
        print("Item number:", book0.number)
        print("Title:", book0.title)
        print("Author:", book0.author)
        print("Genre:", book0.genre)
        print("Price:", book0.price)
        print("===========================================")
        print("Item number:", book1.number)
        print("Title:", book1.title)
        print("Author:", book1.author)
        print("Genre:", book1.genre)
        print("Price:", book1.price)
        print("===========================================")
        print("Item number:", book2.number)
        print("Title:", book2.title)
        print("Author:", book2.author)
        print("Genre:", book2.genre)
        print("Price:", book2.price)
        print("===========================================")
        print("Item number:", book3.number)
        print("Title:", book3.title)
        print("Author:", book3.author)
        print("Genre:", book3.genre)
        print("Price:", book3.price)
        print("===========================================")
        print("Item number:", book4.number)
        print("Title:", book4.title)
        print("Author:", book4.author)
        print("Genre:", book4.genre)
        print("Price:", book4.price)
        print("===========================================")
#This is a class for the user's cart
class Cart(Inventory):
    def __init__(self, make):
        self.make = make
        super().__init__(make)
        self.cartlist = []
    def add_book(self):
        numberbook = int(input("What is the number of the book you would like to buy?"))
        self.cartlist = []
        if numberbook == 1000:
            self.cartlist.append(23.99)
        if numberbook == 1001:
            self.cartlist.append(3.99)
        if numberbook == 1002: 
            self.cartlist.append(3.99)
        if numberbook == 1003:
            self.cartlist.append(9.99)
        if numberbook == 1004:
            self.cartlist.append(61.99)
        if numberbook <= 999 or numberbook >= 1005:
            print("You made a wrong selection")
        return self.cartlist
    def checkout(self):
        total = sum(self.cartlist)
        print("Thank you for shopping! Your total is:", total)
book0 = Book("1000", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
book1 = Book("1001", "My First Human Body Book", "Patricia J. Wyennevand Donald M Silver", "Science", "$3.99")
book2 = Book("1002", "The Runaway Children", "Sandy Taylor", "Fiction", "$9.99")
book3 = Book("1003", "The Tuscan Child", "Rhys Bowen", "Fiction", "$9.99")
book4 = Book("1004", "Science: A Visual Encyclopedia", "Chris Woodford", "Science", "$23.99")
loop = True
myCart = Cart("Cart")
myInventory = Inventory("Inventory")
myCartemp = Cart("Cart")
while(loop):
    print("1: Display Books")
    print("2: Add to Cart")
    print("3: Show Cart")
    print("4: Checkout")
    print("5: Quit")
    userinput = str(input("Select an Option: "))
    if userinput == '1':
        myInventory.display()
        print("These are the book for sale")
        print("You will now be returned to the home screen")
        continue
    if userinput == '2':
        loop2 = True
        while(loop2): 
            myCart.add_book()
            if 1000 == numberbook <= 1005:
                print("Book(s) added successfully!")
            userin2 = str(input("Would you like to continue buying books? Type 1 if yes and 2 if no!"))
            if userin2 == '1':
                print("OK! Let's continue")
                continue
            if userin2 == '2':
                print("OK. You will now be returned to the home screen")
                loop2 = False
        continue
    if userinput == '3':
        print("You have", len(cartlist), "items in your cart, which total to", sum(cartlist))
        continue
    if userinput == '4':
        if myCart:
            print("Your cart is empty!")
            print("You will now be returned to the home screen")
        else:
            myCart.checkout()
            loop = False
    if userinput == '5':
        print("Thank you for shopping!")
        loop = False
myInventory.add_book()

注意:这还没有完成,还有其他错误,或者我还没有编码的区域。我知道如何修复/编码它们,我现在正在处理这个特定的部分


Tags: thetoselfaddnumberforinputif
2条回答

列表索引超出范围意味着对split()方法的调用未找到任何可拆分的内容。因此,不会有索引1(没有拆分,只有一个索引),从而引发列表索引超出范围错误

假设您的booklist.txt只有两个条目,如下所示:

Harry Potter
Grey's Anatomy

然后,你要:

with open('booklist.txt') as f:
    x = f.read().splitlines()
    Content = f.read()

Content顺便说一句,它总是一个空字符串。您在执行x = f.read().splitlines()操作时已经读取了文件,因此文件对象的内部字符指针将已经前进到文件的末尾,这意味着没有要读取的字符了。然而,这只是相切的,并不会导致您的IndexError

现在,x将是两个字符串的列表:["Harry Potter", "Grey's Anatomy"]

稍后,在while循环中,您将执行以下操作:

while(loop):
    myLine = x[y]
    print(myLine)
    myContent = ""
    spliter = myLine.split("\n")
    myContent[spliter[1]] = spliter[2]
    ...
  • 最初,y0,因此myLine将是"Harry Potter"
  • 然后打印"Harry Potter"
  • 然后在换行符上拆分"Harry Potter"。从那以后 如果没有换行符,spliter将是包含 单个字符串:["Harry Potter"]
  • 然后尝试访问该列表的第二个和第三个元素, 两者都不存在,引起了IndexError

字符串中没有可以拆分的换行符,因为在使用f.read().splitlines()时,您已经有效地删除了所有换行符,因为这是分离单个条目的第一步。此外,即使spliter[1]确实存在,也会引发TypeError,因为字符串是不可变的,不支持项赋值。即使这样,您也将字符串视为整数索引,这将引发另一个TypeError

编辑-如果您只想打印文件中每本书的标题(假设每行对应一本书),只需执行以下操作:

with open("booklist.txt", "r") as file:
    for title in file.read().splitlines():
        print(title)

相关问题 更多 >