weixin_52904324
韦俊权\Frank Wei
采纳率0%
2021-03-18 22:24

IndexError: list index out of range

目前代码如下:

def main():
    today = datetime.date.today()

    lis = []
    v = []
    f = open('基金数据.csv', 'rb')
    for line in f:
        line = line.decode().strip('\n')
        sj = line.split(',')
        lis.append('{0:0>6}'.format(sj[0]))
        # sj[4]=sj[4].replace(\,-)
        v.append(sj[1]+' '+sj[2]+' '+sj[3]+' '+sj[4].replace('/','-'))
    dic = dict(zip(lis, v))

出现报错如下:

Traceback (most recent call last):
  File "G:\Pycharm\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\pydevd.py", line 1438, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "G:\Pycharm\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "G:/Python/Pycharm/investment/auto invest.py", line 142, in <module>
    main()
  File "G:/Python/Pycharm/investment/auto invest.py", line 100, in main
    v.append(sj[1]+' '+sj[2]+' '+sj[3]+' '+sj[4].replace('/','-'))
IndexError: list index out of range

新手目前没有头绪是哪方面的问题,请教各位该如何解决,谢谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • secret5 liqiang94 1月前

    python索引列表从0开始,之所以会出现索引越界的错误,是你文件中中至少有一行列数少于5个的。另外,对于csv文件,还是用csv模块来读更稳妥些,可以避免很多坑。

    点赞 评论 复制链接分享
  • hihell 梦想橡皮擦 1月前

    索引超出列表长度

    点赞 评论 复制链接分享
  • qq_34124780 qq_34124780 1月前

    报错是指列表越越界,如果你的sj是有4列的话,sj下标应该从0开始,最大是sj[3],你取sj[4]就是越界

    点赞 评论 复制链接分享

为你推荐