【问题标题】:star wars api => IndexError: list index out of range error星球大战 api => IndexError: 列表索引超出范围错误
【发布时间】:2016-11-04 00:42:36
【问题描述】:

我正在使用来自http://swapi.co/api/ 的星球大战 API。我可以很好地连接到它,我的项目进展顺利。但是,我遇到了以下错误消息:IndexError: list index out of range 错误。查看其他堆栈溢出问题,这似乎是一个错误。关于我的程序,我不确定如何解决它。代码如下:

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

【问题讨论】:

  • 请发布确切的错误消息with traceback
  • 你确定你的n+=1在这里缩进正确吗?
  • n+= 1 缩进正确,因为电影效果很好。我也发布了回溯。
  • n += 1 是最后一行,在循环之外 - 它没有任何作用
  • 是的,很抱歉——我现在修正了对齐方式。我想我找到了问题 - 答案如下,但感谢您的帮助!

标签: python list api off-by-one


【解决方案1】:

像这样使用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 文档了解为什么会发生这种情况。我猜这可能会发生分页。

【讨论】:

  • 是的,它可能正在发生分页 - 我将对此进行测试。你知道解决办法吗?
  • @MikeCuddy 查看响应 json 的 next 属性:"next": "http://swapi.co/api/starships/?page=2" 并获取接下来的 10 个结果等
  • 哦,我想我明白了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 2017-07-02
  • 2018-04-22
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多