尝试使Python代码经过IndexError :,然后继续

时间:2019-02-14 04:18:48

标签: python json indexing

请帮忙,我是Python的新手,已经研究了几个小时。我正在尝试运行特定的JSON代码,但是不知道JSON列表的长度为16、15、14或13个部分。因此,我想运行代码,直到达到最高编号为止。 这就是我所拥有的:

import requests     
api_address = 'http://api.openweathermap.org/data/2.5/forecast/daily? 
zip=10603&cnt=16&appid=fe0b46e2c4f3c410fc3f8ac8d3a17600&q'          
zip_code =  79326   
url = api_address + str(zip_code)           
json_data = requests.get(url).json()
formatted_data1 = json_data['list'][16]['temp']
formatted_data2 = json_data['list'][15]['temp']
formatted_data3 = json_data['list'][14]['temp']
formatted_data4 = json_data['list'][13]['temp']
try:
print (formatted_data1)
    try:
    print (formatted_data2) 
        try:
        print (formatted_data3) 
            try:
            print (formatted_data4)

我从中收到“ SyntaxError:解析时发生意外的EOF”错误,但我运行此操作是为了避免出现“ IndexError:列表索引超出范围”

"print(formatted_data1, formatted_data2, formatted_data3, formatted_data4) " 

最后

请告知

3 个答案:

答案 0 :(得分:1)

您收到语法错误,因为您没有将 try 与任何 除外。

try:
    print(formatted_data1)
except:
    print('These excepts are necessary')
try:
    print (formatted_data2) 
except:
    print('These excepts are necessary')
try:
    print (formatted_data3) 
except:
    print('These excepts are necessary')
try:
    print (formatted_data4)
except:
    print('These excepts are necessary')

对于您要解决的问题,可以使用类似...的方法来改进您的方法。

parts = json_data['list']

...做类似...

for p in parts:
    print(p['temp'])

答案 1 :(得分:0)

SyntaxError是由于缩进错误引起的

# Error
try:
print (formatted_data1)

# No Error
try:
    print (formatted_data1)

IndexError是由于尝试访问超出有效索引的值而引起的。例如,alength中的3,对a的所有有效访问是a[0]a[1]a[2]。如果您尝试获得a [3],则将获得IndexError

以下代码

a = ['a','b','c']
print(len(a))
print(a[3])

屈服

$ python test.py
3
Traceback (most recent call last):
      File "test.py", line 3, in <module>
          print(a[3])
          IndexError: list index out of range

通常错误消息会告诉您错误在哪里,例如上述消息中的File "test.py", line 3

我不确定您是否只想要最后一个值。

如果是这种情况,请尝试使用len函数来获取长度,然后再尝试获取值,以确保您永远不会尝试超过最后一个。 - 1,因为它zero-based index

import requests

api_address = 'http://api.openweathermap.org/data/2.5/forecast/daily?zip=10603&cnt=16&appid=fe0b46e2c4f3c410fc3f8ac8d3a17600&q'
zip_code =  79326
url = api_address + str(zip_code)
json_data = requests.get(url).json()

data_length = len(json_data['list']) - 1
print(data_length)

formatted_data = json_data['list'][data_length]['temp']
print(formatted_data)

调试提示:使用print函数打印出该值,看是否有意义。

答案 2 :(得分:-1)

当您尝试访问而不是打印数据时,会发生IndexError,因此在打印语句周围放置try块也是迟到。

但是更好的解决方案是根本不使用try;相反,您可以查看列表的长度,因此不必猜测存在多少元素:

if len(json_data['list']) >= 14:
    print (json_data['list'][13]['temp'])
if len(json_data['list']) >= 15:
    print (json_data['list'][14]['temp'])
if len(json_data['list']) >= 16:
    print (json_data['list'][15]['temp'])
if len(json_data['list']) >= 17:
    print (json_data['list'][16]['temp'])