0

我有一个保存为元组列表的数据库,每个元组都有 4 个元素。第一个元素是书号,第二个元素是书名,第三个元素是书的作者,第四个元素是书的出版年份。

我需要一个名为 的函数,它以元组列表和字符串findBook(L, keyword)的形式接收书籍,并返回其中的所有内容。应该是这样的:keywordtuples of bookskeywordtuple of the book

(BookNumber, BookName, Author, YearPublished)

如何编写一个搜索引擎来帮助我们找到这些特定的书籍?

我试图从这个开始,但它不起作用:

def findBook(L,keyword):

    for i in L:
        BookNumber=i[0]
        BookName=i[1]
        Author=i[2]
        YearPublished=i[3]
        i=(BookNumber,BookName,Author,YearPublished)

        if keyword == str(BookName) or keyword==BookNumber or keyword==str(Author) or keyword==str(YearPublished):
            return i

所以如果我有一本哈利波特书,我输入关键字:“哈利”,它应该返回所有的整个元组。

4

1 回答 1

0

您可以遍历可能具有keyword您正在寻找的条目,将它们分组到一个列表中,该列表应在流程结束时返回:

def findBook(L, keyword):

    books = list()
    for book in L:

        book = tuple(entry for entry in book)
        if [i for i in book if str(i).find(keyword) != -1]:
            books.append(book)

    return books

L = [(2,"harry potter and the prisoner of azkaban ","J.K Rowling","1998"),
        (3,"harry potter and the half blood prince","J.K Rowling","2007"),
        (6,"Harry potter and deathly hallows","J.K Rowling","2010"),
        (8,"The secret","someone","2009")]

print findBook(L, "harry")

输出:

[(2, 'harry potter and the prisoner of azkaban ', 'J.K Rowling', '1998'), (3, 'harry potter and the half blood prince', 'J.K Rowling', '2007')]

注意没有找到第三个条目,因为它keyword是“harry”而不是“Harry”,要进行不区分大小写的搜索,请使用:

def findBook(L, keyword):

    books = list()
    keyword = keyword.tolower()

    for book in L:

        book = tuple(entry for entry in book)
        if [i for i in book if str(i).tolower().find(keyword) != -1]:
            books.append(book)

    return books
于 2012-12-27T13:20:53.840 回答