我想按圖書出版日期對 Google Books API 回傳的圖書串列進行排序。資料看起來像這樣:
{
"kind": "books#volumes",
"totalItems": 506,
"items": [
{
...
"volumeInfo": {
"title": "RHYTHM OF WAR PART ONE",
"authors": [
"BRANDON SANDERSON"
],
"publishedDate": "2023-03-16",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "1473233372"
},
...
},
我嘗試過的是首先將書籍隔離在一個新串列中,如下所示:
myList = myList["items"]
然后按日期時間對新串列進行排序。
myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))
我收到以下錯誤訊息:
myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["publishedDate"]["volumeInfo"], '%Y-%m-%d'))
TypeError: list indices must be integers or slices, not str
我也嘗試過使用 itemgetter 方法,但到目前為止還沒有成功。
API 呼叫的結果可以按發布日期排序,如下所示:
https://www.googleapis.com/books/v1/volumes?q=inauthor:brandon sanderson&orderBy=newest
但是我將多次呼叫的結果添加到一個串列中,并希望能夠按發布日期對所有書籍進行排序。
uj5u.com熱心網友回復:
問題必須在您的代碼中的其他地方,因為這對您所說的所做的作業最少,但沒有問題:
from json import load
from urllib.request import urlopen
from datetime import datetime
with urlopen('https://www.googleapis.com/books/v1/volumes?q=inauthor:brandon sanderson&orderBy=newest') as r:
data = load(r)
items = data['items']
sorted_items = sorted(items, key=lambda d: datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))
print(sorted_items)
如果您仍然有問題,請提供一個最小的、可重現的示例。
uj5u.com熱心網友回復:
我發現你的問題了!
在你的第二個myListSorted陳述句中,你得到了錯誤的字典引數!
試試這個:
myListSorted = sorted(myList, key=lambda d: datetime.datetime.strptime(d["volumeInfo"]["publishedDate"], '%Y-%m-%d'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/390723.html
