python - 星球大战 api => IndexError : list index out of range error

标签 python list api off-by-one

我正在使用 http://swapi.co/api/ 的星球大战 API 。我可以很好地连接到它,并且我的项目进展顺利。但是,我遇到以下错误消息:IndexError:列表索引超出范围错误。查看其他堆栈溢出问题,这似乎可能是一个错误。我不确定如何修复我的程序。这是代码:

url = ('http://swapi.co/api/' + str(view))
#Setting up a get request to pull the data from the URL
r = requests.get(url)
if r.status_code == 200:
   print("status_code", r.status_code)
else:
  print("Sorry it appears your connection failed!")

#Storing the API response in a variable
response_dict = r.json()
print("There are currently", response_dict['count'], "items to view")

repo_dicts = response_dict['results']

num = 0
while num < response_dict['count']:
  if view == 'films':
    repo_dict = repo_dicts[num]['title']
    print(str(num) + " " + repo_dict)
  elif view == 'starships':
    repo_dict = repo_dicts[num]['name']
    print(str(num) + " " + repo_dict)
  num += 1

现在给我带来问题的行是在 elif view == 'starships' 区域。实际上,如果访问 API,您可以看到某些类别,例如电影、人物、星际飞船等。除电影外,所有类别都包含超过 10 种内容。我还注意到,如果我转到 http://swapi.co/api/starships/4/不会找到任何细节。某些类别没有数据是否会导致我的问题?感谢您的见解!!

这是回溯错误消息:

Traceback (most recent call last):
  File "main.py", line 102, in <module>
  main()
  File "main.py", line 98, in main
  began()
  File "main.py", line 87, in began
  connect(view)
  File "main.py", line 31, in connect
  repo_dict = repo_dicts[num]['name']
 IndexError: list index out of range

最佳答案

使用 foreach 循环迭代结果,如下所示:

for item in repo_dicts:
    if view == 'films':
        repo_dict = item['title']
        print(str(num) + " " + repo_dict)
    elif view == 'starships':
        repo_dict = item['name']
        print(str(num) + " " + repo_dict)

原因是因为 api 在 response_dict['results'] 中返回 10 个项目,但 response_dict['count'] 为 37。请参阅 api 文档以了解发生这种情况的原因。我猜这可能会发生分页。

关于python - 星球大战 api => IndexError : list index out of range error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38148186/

相关文章:

javascript - Fetch API 是 ECMAscript 功能吗?

python - 将列表列表转换为字典列表

java - 在 Java 中添加到列表中的系列

java - 返回数组列表对象 java 中的列表

list - 如何在 ELisp 中插入列表的中间?

java - 通过编程语言访问 Skype

python - 如何正确地将 JSON 转换为 Python 对象?

Python 线程不在 C++ 应用程序嵌入式解释器中运行

python - 如何在 PyDev 中禁用模板调试

api - 如何从服务器中获取视频?