我真的不知道这里发生了什么 - 让我概述一下代码。
我从SFG WorldCup API中提取数据。
今天早些时候API的示例输出:
[
{
"match_number": 26,
"location": "Arena da Baixada",
"datetime": "2014-06-20T19:00:00.000-03:00",
"status": "in progress",
"home_team": {
"country": "Honduras",
"code": "HON",
"goals": 1
},
"away_team": {
"country": "Ecuador",
"code": "ECU",
"goals": 2
},
"winner": null,
"home_team_events": [
{
"id": 290,
"type_of_event": "yellow-card",
"player": "Bernardez",
"time": "7"
},
{
"id": 291,
"type_of_event": "goal",
"player": "Costly",
"time": "31"
},
{
"id": 294,
"type_of_event": "substitution-in halftime",
"player": "J.C. Garcia",
"time": "46"
},
{
"id": 297,
"type_of_event": "substitution-in",
"player": "M. Martinez",
"time": "71"
},
{
"id": 301,
"type_of_event": "substitution-in",
"player": "M. Chavez",
"time": "83"
},
{
"id": 293,
"type_of_event": "yellow-card",
"player": "Bengtson",
"time": "453"
}
],
"away_team_events": [
{
"id": 292,
"type_of_event": "goal",
"player": "E. Valencia",
"time": "34"
},
{
"id": 295,
"type_of_event": "yellow-card",
"player": "A. Valencia",
"time": "57"
},
{
"id": 296,
"type_of_event": "goal",
"player": "E. Valencia",
"time": "65"
},
{
"id": 298,
"type_of_event": "yellow-card",
"player": "E. Valencia",
"time": "73"
},
{
"id": 299,
"type_of_event": "yellow-card",
"player": "Montero",
"time": "80"
},
{
"id": 300,
"type_of_event": "substitution-in",
"player": "Mendez",
"time": "82"
},
{
"id": 302,
"type_of_event": "substitution-in",
"player": "Gruezo",
"time": "83"
}
]
}
]
有了这些数据,我的问题是在for循环中获取数据是有效的,但是在下面的while循环中却没有。
resp
是来自api的回应...
for jogo in resp.json():
score = jogo['home_team']['goals']
jogo = resp.json()
while True:
newscore = int(jogo['home_team']['goals'])
实际代码略有不同(while循环中的jogo['home_team']['goals']
位于if
语句中,但这是它的基本框架。
我得到的错误是while
中的错误,它显示TypeError: list indices must be integers, not str
我不确定我是否将它与整数进行比较(我将其包含在int()
中)。
造成这种情况的原因是什么,为什么不在第一次调用它。
谢谢!
evamvid
PS让我知道这是否有任何意义=)
答案 0 :(得分:0)
发布新代码更有意义:
# here, jogo takes the value of each dict{} within the outer list[]
for jogo in resp.json():
score = jogo['home_team']['goals']
# while here it is the outer list itself
jogo = resp.json()
while True:
newscore = int(jogo['home_team']['goals'])
如果你知道列表中只有一个结果,你可以使用
jogo = resp.json()[0]
错误告诉你jogo
需要一个整数索引(暗示它是一个列表类型或类似的),但是你传递一个字符串索引(显示你预期它是一个字典)。这是导致错误的声明:
...jogo['home_team']...
外部int
电话无效。