python : 列表索引超出范围错误 1
python : list index out of range error 1
我正在尝试检查我返回的数组是否为空。
我正在尝试的代码是:
if (r.json()['negative'][0]['topic']) == "":
我得到的错误是索引超出范围错误。
我知道这意味着数组中没有任何内容,但我的代码崩溃了,因为它没有返回任何内容。
有什么想法吗?
不要将所有内容都放在一行中,否则您将无法知道到底发生了什么。
data = r.json()
if 'negative' not in data:
print('negative key is missing')
elif len(data['negative']) == 0:
print('no items in the negative list')
elif 'topic' not in data['negative'][0]:
print('topic is missing')
elif data['negative'][0]['topic'] == '':
print('topic is empty')
else:
# now you can access it safely
print(data['negative'][0]['topic'])
您正在尝试访问空数组 r.json()['negative'] 中的第一个元素,这导致您的代码失败。
检查 "negative" key 是否不是空数组然后你可以检查你的条件。
if (r.json()['negative']:
if (r.json()['negative'][0]['topic']) == "":
因为你要深入 3 字典列表中的一组字典 - 你几乎肯定需要按照其他人的建议检查每个容器的长度(或检查键是否在字典中) ,或者它被一些人认为更 pythonic 只是捕获异常并继续:
try:
if (r.json()['negative'][0]['topic']) == "":
# do stuff
except IndexError:
# do other stuff
这是常用的It is better to ask forgiveness than to ask permission
原则。
我正在尝试检查我返回的数组是否为空。
我正在尝试的代码是:
if (r.json()['negative'][0]['topic']) == "":
我得到的错误是索引超出范围错误。
我知道这意味着数组中没有任何内容,但我的代码崩溃了,因为它没有返回任何内容。
有什么想法吗?
不要将所有内容都放在一行中,否则您将无法知道到底发生了什么。
data = r.json()
if 'negative' not in data:
print('negative key is missing')
elif len(data['negative']) == 0:
print('no items in the negative list')
elif 'topic' not in data['negative'][0]:
print('topic is missing')
elif data['negative'][0]['topic'] == '':
print('topic is empty')
else:
# now you can access it safely
print(data['negative'][0]['topic'])
您正在尝试访问空数组 r.json()['negative'] 中的第一个元素,这导致您的代码失败。
检查 "negative" key 是否不是空数组然后你可以检查你的条件。
if (r.json()['negative']:
if (r.json()['negative'][0]['topic']) == "":
因为你要深入 3 字典列表中的一组字典 - 你几乎肯定需要按照其他人的建议检查每个容器的长度(或检查键是否在字典中) ,或者它被一些人认为更 pythonic 只是捕获异常并继续:
try:
if (r.json()['negative'][0]['topic']) == "":
# do stuff
except IndexError:
# do other stuff
这是常用的It is better to ask forgiveness than to ask permission
原则。