【问题标题】:Finding a variable in a list with other stored variables from a class查找列表中的变量以及类中的其他存储变量
【发布时间】:2015-08-06 00:39:15
【问题描述】:

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

myBooks = []

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

myBook = Class
myBooks.append(myBook)

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

感谢任何帮助。 谢谢

【问题讨论】:

  • 一些代码会有帮助。
  • 很不清楚你在问什么。
  • 那为什么不在发帖之前搞清楚呢?!
  • 已尝试清理并添加代码的简短摘要。干杯

标签: python list class


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    不是 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)
    

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 2021-01-24
      • 1970-01-01
      • 2013-01-29
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多