我正在嘗試解決一個練習(xí),基本上,我必須解析一個 JSON 頁面并搜索一個對象。如果未找到該對象,則我必須在下一頁中搜索它。如果person我要查找的內(nèi)容在第一頁上,那么我通過了測試,但如果它在另一頁上,則我會失敗。我檢查并正確解析了每個頁面,但return如果它不在第一頁上,則始終未定義。這是我的代碼:import urllib.requestimport jsonclass Solution: def __new__(self, character): url = 'https://challenges.hackajob.co/swapi/api/people/' numberOfFilms = 0 # # Some work here; return type and arguments should be according to the problem's requirements # numberOfFilms = self.search(self,character,url) return numberOfFilms def search(self, character,url): numberOfFilms = 0 found = False with urllib.request.urlopen(url) as response: data = response.read() jsonData = json.loads(data.decode('utf-8')) for r in jsonData['results']: if r['name'] == character: return len(r['films']) if (jsonData['next']): nextPage = jsonData['next'] self.search(self,character,nextPage)
搜索多個頁面進(jìn)行匹配
慕運(yùn)維8079593
2021-08-05 17:29:11