【发布时间】:2023-03-14 20:25:01
【问题描述】:
我已经编写了访问数据库的函数。
名为Books 的表有:
- a `book_id` TEXT column,
- a title TEXT column, and
- an author TEXT column.
对于第一个,run_query是一个连接数据库的函数。
get_book_cnt_per_author 是一个以这种形式返回元组列表的函数:
'author', number of books
我不知道如何通过循环使用run_query 函数。我写的东西总是得到None。
我不知道我的问题出在哪里。我只为每位作者获得一本书。
请告诉我是什么问题。
def get_books(db, book_cnt_list, book_cnt): """ (str, list of tuple, int) -> list of str
Precondition: the elements in book_cnt_list are sorted
in ascending order by author name.
Return a list of all the book titles whose authors
each have book_cnt books in the database with name db
according to the book_cnt_list. The book titles should be in
ascending order for each author, but not for the entire list.
Follow ascending order across authors, that is, the order
authors appear in book_cnt_list that is already sorted by
author name.
>>> author_cnt_list = get_book_cnt_per_author("e7_database.db")
>>> books_list = get_books("e7_database.db", author_cnt_list, 10)
>>> books_list[0]
'A Christmas Carol'
>>> books_list[9]
'The Life and Adventures of Nicholas Nickleby'
>>> books_list[10]
'Disgrace'
>>> books_list[-1]
'Youth'
"""
# HINT: First figure out which authors have book_cnt books
# using the book_cnt_list. Then, access the database db
# to retrieve the required information for those authors.
# Do not call any other of your E7 functions other than run_query.
list1 = []
for i in book_cnt_list:
if i[1] == "book_cnt":
list1.append(i[0])
for j in list1:
return run_query(my_db, '''SELECT title FROM Books OREDER BY Books.title ASC WHERE Books.author = ? ''', (j))
def create_author_dict(db): """ (str) -> {str: list of str}的字典
Return a dictionary that maps each author to the books they have written
according to the information in the Books table of the database
with name db.
>>> author_dict = create_author_dict('e7_database.db')
>>> author_dict['Isaac Asimov'].sort()
>>> author_dict['Isaac Asimov']
['Foundation', 'I Robot']
>>> author_dict['Maya Angelou']
['I Know Why the Caged Bird Sings']
"""
con = sqlite3.connect(db)
cur = con.cursor()
cur.execute('''SELECT author, title FROM Books WHERE Books.author = ?''')
new_list = cur.fetchall()
new_dict = {}
for i in new_list:
key = i[0]
value = i[1:]
new_dict.update({key: list(value)})
con.commit()
cur.close()
con.close()
return new_dict
【问题讨论】:
-
尽可能贴出这两个函数的代码。
-
我在答案中发布了它。请看看它,看看我的问题是什么。谢谢
-
您应该为您的问题编写代码,而不是在答案部分。我不能出错,但我鼓励您打印
value变量的值,以确保您从数据库中获得的每位作者不止一本书。
标签: database python-3.x loops dictionary sqlite