首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不管情况如何,作者完全匹配的过滤器

不管情况如何,作者完全匹配的过滤器
EN

Stack Overflow用户
提问于 2022-11-18 15:28:24
回答 1查看 36关注 0票数 0

我有目录和书的链接列表。我试图通过作者过滤并返回与之完全匹配的书籍,然而,它说,每当我运行它时,我的图书类型就没有这样的属性。我也尝试大写作者的名字,以便它是一致的和匹配将返回,即使输入是不同的大小写。

代码语言:javascript
复制
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]

我试图断言,如果作者与目录中的书籍相匹配,列表将随书返回。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-18 15:41:43

您不需要复制您的lst,因为您的生成器在下面列出了一个新的列表。我也不明白你为什么要使用.capitalize()

问题是,在您的list comprehension中,您要遍历每个book,调用当前的Book "author",然后尝试对author进行访问。然而,author是一个不能大写的Book。在您的代码中,您需要调用author.author.capitalize(),或者只需使用以下命令:

代码语言:javascript
复制
def filter_by_author(self, author):
  author = author.lower()
  return [book for book in self.lst if book.author.lower() == author]

编辑以响应评论

在python中,您可以很容易地检查一个字符串是否包含某个子字符串:

代码语言:javascript
复制
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"

代码语言:javascript
复制
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"]参数默认值为" ",因此不需要传递它。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74491900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档