使用类中的其他存储变量查找列表中的变量

时间:2015-05-24 11:25:54

标签: python list class

我想在列表中搜索标题,然后删除标题以及随其存储的作者和评级。

myBooks = []

class = Class
title = input("title")
author = input("author")
rating = input("rating")

myBook = Class
myBooks.append(myBook)

然后我想要一个方法来搜索列表中的标题,如果标题存在,则删除标题和作者以及给予该标题的评级。

感谢任何帮助。 谢谢

2 个答案:

答案 0 :(得分:0)

你所追求的并不是很明显,但我很快就把它扔了。使用标题作为唯一键是一个坏主意,所以我建议更改它,这只是一个起点:)

class BookClass:
    def __init__(self, **kwargs):
        self.kwargs = kwargs

    def add(self, title, author, rating):
        self.kwargs[title] = (author, rating)

    def remove(self, title):
        return self.kwargs.pop(title)

    #Example of how you'd go about getting all the authors or whatever
    def authors(self):
        for title in self.kwargs:
            print self.kwargs[title][0]

使用您的代码添加到它:

title = input("title")
author = input("author")
rating = input("rating")

myBooks = BookClass()
myBooks.add(title, author, rating)

搜索列表并删除图书

title = input("title")
author, rating = myBooks.remove(title)

答案 1 :(得分:0)

它并非100%明确表示您希望首先将书籍添加到列表中,但我认为情况确实如此。

这不能处理两本书具有相同标题的情况,在这种情况下,您可能希望像ISBN这样更独特的东西成为关键。

使用dict存储您的图书,并通过title将其设为关键字。

# myBooks dict indexed by book title
myBooks = {}

class BookNotFoundException(Exception):
    pass

def addbook(title, author, rating):
    ''' adds a book '''
    myBooks[title] = {'author':author, 'rating':rating}

def removebook(title):
    ''' removes a book otherwise throws an exception '''
    if title in myBooks:
        del myBooks[title]
    else:
        raise BookNotFoundException('Book %s not found in list' % title)

# input the params
title = input("title")
author = input("author")
rating = input("rating")

## call add book
addbook(title, author, rating)

## print the dict to see what you have
print(myBooks)

# enter item to remove
toremove = input('enter title of book to remove: ')

try:
    # try to remove book
    removebook(toremove)
    print('removed ok')
except BookNotFoundException as e:
    print('didnt remove ok')

# convince yourself its empty now
print(myBooks)