我有目录和书的链接列表。我试图通过作者过滤并返回与之完全匹配的书籍,然而,它说,每当我运行它时,我的图书类型就没有这样的属性。我也尝试大写作者的名字,以便它是一致的和匹配将返回,即使输入是不同的大小写。
class Book:
def __init__(self, title, author, year):
if not isinstance(title, str):
raise Exception("title must be a string")
if not isinstance(author, str):
raise Exception("author must be a string")
if not isinstance(year, int):
raise Exception("year must be an integer")
self.title = title
self.author = author
self.year = year
def __eq__(self, other):
if isinstance(other, Book):
return self.title == other.title and \
self.author == other.author and \
self.year == other.year
return NotImplemented
def __repr__(self):
return f"{repr(self.title)} by {repr(self.author)} {self.year})"
class Catalog:
def __init__(self):
self.lst = []
def filter_by_author(self, author):
xs = self.lst.copy()
xs = [author.capitalize() for author in xs]
if author.upper() in xs:
return self.lst
# driver
b1 = Book("1984", "George Orwell", 1949)
b2 = Book("Brave new world", "Aldous Huxley", 1932)
b3 = Book("El aleph", "Jorge Louis Borges", 1949)
b4 = Book("The devils of Loudun", "Aldous Huxley", 1952)
cat = Catalog()
cat.add(b1)
cat.add(b2)
cat.add(b3)
cat.add(b4)
la = cat.filter_by_author("aldous huxley")
assert la == [b2, b4]我试图断言,如果作者与目录中的书籍相匹配,列表将随书返回。
发布于 2022-11-18 15:41:43
您不需要复制您的lst,因为您的生成器在下面列出了一个新的列表。我也不明白你为什么要使用.capitalize()
问题是,在您的list comprehension中,您要遍历每个book,调用当前的Book "author",然后尝试对author进行访问。然而,author是一个不能大写的Book。在您的代码中,您需要调用author.author.capitalize(),或者只需使用以下命令:
def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if book.author.lower() == author]编辑以响应评论
在python中,您可以很容易地检查一个字符串是否包含某个子字符串:
def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if author in book.author.lower()]我不确定这是你想要的,因为"John" in "Johnathan"是真实的。所以你可能会想要检查其中的名字是否是"John"
def filter_by_author(self, author):
author = author.lower()
return [book for book in self.lst if author in book.author.lower().split()]这首先将字符串拆分为一个特定的字符串。例如:"John Nathan Last-name".split(" ") == ["John", "Nathan", "Last-name"]参数默认值为" ",因此不需要传递它。
https://stackoverflow.com/questions/74491900
复制相似问题