我正在尝试检查我返回的数组是否为空。
我正在尝试的代码是:
if (r.json()['negative'][0]['topic']) == "":
我得到的错误是索引超出范围错误。
我知道这意味着数组中没有任何内容,但是我的代码崩溃了,因为它没有返回任何内容。
有任何想法吗?
我正在尝试检查我返回的数组是否为空。
我正在尝试的代码是:
if (r.json()['negative'][0]['topic']) == "":
我得到的错误是索引超出范围错误。
我知道这意味着数组中没有任何内容,但是我的代码崩溃了,因为它没有返回任何内容。
有任何想法吗?
您正在尝试从空数组 r.json()['negative'] 访问第一个元素,这导致您的代码失败。
检查“负”键是否不是空数组,然后您可以检查您的情况。
if (r.json()['negative']:
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'])
因为您要深入到字典列表中的一组字典中 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
是常用的原理。