为什么这个列表索引超出范围?

时间:2017-12-15 12:57:04

标签: python list index-error

我有一个'test.txt'文件,例如包含:

的示例
 --
a
 --
b
 --
c

和我的Python代码:

x = ['a','b','c']
i=1
with open("test.txt", "r") as fin:
    with open("result.log", "w") as fout:
        for line in fin:
            if line.startswith(' --'):
                fout.write(line.replace(' --','use {}'.format(str(x[i-1]))))
                i+=i
            else:
                fout.write(line)

但结果是:

fout.write(line.replace(' --','use {}'.format(str(x[i-1]))))
IndexError: list index out of range

应该工作......任何人都可以帮助我吗?我想得到结果:

use a
a
use b
b
use c
c

3 个答案:

答案 0 :(得分:1)

在Python中,增量运算符看起来像这样i+=1但是你尝试使用i+=i它总是递增i = i + i

  

当i = 1时然后增加i = 2

     

当i = 2时然后增加i = 4

数组中有三个元素,因此它可以提供错误索引。

答案 1 :(得分:0)

使用0初始化i,然后在循环中将其递增1.此外,您不必调用str()因为format()为您执行此操作。试试这个:

x = ['a', 'b', 'c']
i = 0

with open("test.txt", "r") as fin, open("result.log", "w") as fout:    
    for line in fin:
        if line.startswith(' --'):
            fout.write(line.replace(' --','use {}'.format(x[i])))
            i += 1
        else:
            fout.write(line)

写入result.log的输出:

use a
a
use b
b
use c
c

答案 2 :(得分:0)

public static function sunrise(Carbon $date, $latitude, $longitude){ $timestamp = $date->getTimestamp(); return Carbon::createFromTimestamp(date_sunrise($timestamp, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude)); } public static function sunset(Carbon $date, $latitude, $longitude){ $timestamp = $date->getTimestamp(); return Carbon::createFromTimestamp(date_sunset($timestamp, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude)); } 导致异常。你可以使用:

i+=i
相关问题