【问题标题】:index list error google app engine索引列表错误谷歌应用引擎
【发布时间】:2012-03-26 08:05:32
【问题描述】:
file_name = files.blobstore.create(mime_type='application/ms-excel', _blobinfo_uploaded_filename='sample.xls')
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet('Sheet 1')
    stringa = str(newfile.text)
    s3 = stringa.split('\n')
    i=1
    for riga in s3:
        s2=riga.split()
        try:
            x  = float(s2[0])
            y = float(s2[1])
            sheet.write(i, 1, '%g' %x)
            sheet.write(i, 2, '%14.3e' %y)
        except:
            sheet.write(i, 1, '%s' %s2[0])
            sheet.write(i, 2, '%s' %s2[1])
        i=i+1

文件“/base/data/home/apps/s~marco-busso/1.357756583016056739/helloworld.py”,第 140 行,在帖子中 sheet.write(i, 1, '%s' %s2[0]) IndexError: 列表索引超出范围

为什么?

【问题讨论】:

    标签: google-app-engine python-2.7


    【解决方案1】:

    显然s2 是空的,这意味着riga 是一个空字符串。 stringa 是否连续有多个 '\n'?检查newfile.text,可能那里是一个空行。

    为了防止出错,可以将循环体包裹在if语句中,如:

    for riga in s3:
        if riga:
            s2=riga.split()
            try:
                x  = float(s2[0])
                y = float(s2[1])
                sheet.write(i, 1, '%g' %x)
                sheet.write(i, 2, '%14.3e' %y)
            except:
                sheet.write(i, 1, '%s' %s2[0])
                sheet.write(i, 2, '%s' %s2[1])
            i=i+1
    

    【讨论】:

    • 当然。例如,您可以将for 循环的内容包装在if riga: 语句中。
    • 好。我还可以指出,通常有用的答案是提问者accepted,以表明问题已解决。这也适用于您之前的问题。
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多