尝试访问词典列表的最后一个值时遇到关键错误

问题描述

背景:编写程序以从Web提取选项链数据。 为了显示代码的编写方式,请看下面。 (不是实际的代码,而只是一种表示形式) 该代码主要包含注释,以描述每个代码块中正在发生的事情。 问题是,当我第一次运行代码时,如果不执行条件操作,则会在其中一行代码。我在代码本身中添加了注释,以使这一点更清楚。当我运行代码时,出现错误:

回溯(最近通话最近): 文件“ D:\ AC \ Coursera Course \ Python for Everyone \ Course 1- Python入门Python \ Python程序\ nse_data.py”,第222行,在 主要() 主文件“ D:\ AC \ Coursera Course \ Python for Everyone \ Course 1- Python入门Python \ Python程序\ nse_data.py”,第218行 data_log(r) 文件“ D:\ AC \ Coursera Course \ Python for Everyone \ Course 1- Python入门Python \ Python程序\ nse_data.py”,行187,在data_log中 all_data ['Time'] = df_list [-1] [0] ['Time'] KeyError:-1

import requests
import json


url = 'some url'
data_list = [] # needs to be a list of dictionaries that contain data
# creating 1 file to store all the data for each day,this will be present in 'data_log' folder in current directory after the 1st time program runs for the day
log_file = os.path.join('data_log','oi_records_{0}.json'.format(datetime.datetime.now().strftime('%d%m%y')))

def get_OI_data:
    # No problem in this function
    r = requests(url).json()
    # fetched data has this format: 
    https://drive.google.com/file/d/1Z0Va8obzvW29ZlYdrAljFgdUlUlqT4qy/view?usp=sharing
    #return dict data
    return r

def write_OI_data:
    # No problem in this function
    # function to write data into an excel file
    print('data written to excel')

def data_log(r):
    
    # the second time we reach here,data_list will contain value of the key records from 'all_data'
    all_ce = [items['CE']for items in r['records']['data'] if 'CE' in items]
    all_pe = [items['PE']for items in r['records']['data'] if 'PE' in items]
    # converting into a dataframe
    all_df_ce = pd.DataFrame(all_ce)
    all_df_pe = pd.DataFrame(all_pe)
    # adding a new column type
    all_df_ce['Type'] = 'CE'
    all_df_pe['Type'] = 'PE'
    all_data = pd.concat([all_df_ce,all_df_pe])

    # adding 2 if conditions to check if the data is duplicate or not
    # problem in line below,Why is the program entering inside condition below the 1st time time program runs??
    # since data_list is initiated as empty list,its length should be 0 hence both conditions below should be skipped the 1st time data in fetched in a day
    if len(data_list) > 0:
    # trying to set time column in all_data equal to the time value in last value of data_list
        all_data['Time'] = data_list[-1][0]['Time'] 
    # Problem in above line...program entering the the conditional block even though data_list is initiated as null

    if len(data_list) > 0 and all_data.to_dict('records') == data_list[-1]:
        print('Duplicate data present,no need to record: ')
        sleep(10)
        # need to add more code here to reroute the flow of the dode.

    all_data['Time'] = datetime.datetime.now().strftime('%H:%M')
    data_list.append(all_data.to_dict('records'))
    with open(log_file,'w') as file:
        file.write(json.dumps(data_list,indent = 4,sort_keys = True))

def main():
    r = get_OI_data()

    write_OI_data(r)
    global data_list
    try:
        # Reading log file if it exists other wise setting data_list as an empty list
        data_list = json.loads(open(log_file).read())
    except:
        print('Error reading Previous log file: ')
        data_list = []
    data_log(r)

if __name__ == '__main__':
    main()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...