星球大战api => IndexError:列表索引超出范围错误

时间:2016-07-01 14:40:55

标签: 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

1 个答案:

答案 0 :(得分:3)

使用 <?php $json = '{"name":"John Doe", "records":[{"sample": "sample","fields":{"date":"Sample Date","Sample Field":"Sample value", "id": "sampleid"}}]}'; $json = json_decode($json , true); $dates = []; foreach($json['records'] as $record) { $date = $record['fields']['date']; if(!isset($dates[$date])) $dates[]= $date; } var_dump($dates); 循环迭代结果:

foreach

原因是因为api在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) 中返回了10个项目,但是response_dict['results']是37.请参阅api文档,了解为什么会发生这种情况。我猜这可能是分页发生的。