访问python列表中的前一个元素

时间:2017-01-15 18:56:49

标签: python list loops range

这看起来很简单,我不明白为什么它不起作用。

此代码使用[i-1]访问列表中的上一个元素:

# I found this on Stack Overflow and it works
l=[1,2,3]
for i,item in enumerate(l):
    if item==2:
        get_previous=l[i-1]
        print "get_previous = " + str(get_previous)

这不会访问上一个列表元素,即使它存在,因为它打印为line1[0]

# What happens to $1,000 if you earn 1,2,3% interest for 30 years?
initial_amount = 1000.00
ratio1 = 1.01
ratio2 = 1.02
ratio3 = 1.03
line1 = []
line2 = []
line3 = []
line1.append(initial_amount)
line2.append(initial_amount)
line3.append(initial_amount)
print "line1[0] = " + str(line1[0])
for index in range(0, 30):
    print "index outside of if = " + str(index)
    if(index > 0):
        print "index inside if = " + str(index)
        line1[index] = line1[index-1] * ratio1
        line2[index] = line2[index-1] * ratio2
        line3[index] = line3[index-1] * ratio3

输出结果为:

get_previous = 1
line1[0] = 1000.0
index outside of if = 0
index outside of if = 1
index inside if = 1
Traceback (most recent call last):
    line1[index] = line1[index-1] * ratio1
IndexError: list assignment index out of range

1 个答案:

答案 0 :(得分:3)

您应该使用line1.append(..)作为:

line1.append(line1[index-1] * ratio1)
line2.append(line2[index-1] * ratio2)
line3.append(line3[index-1] * ratio3)

因为您试图在列表中当前不存在的第1个索引处更新值(即列表line1的长度为1)。为了最后插入值,python有list.append(..)方法。