访问python列表中的上一个元素
这看起来很简单,我不明白为什么它不起作用 此代码使用访问python列表中的上一个元素,python,list,loops,range,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) 这不会访问上一个列表元素,即使它存在,因为它被打印
[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
您应该使用
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(..)
方法。它失败了,因为list[index]
第一次不存在。您需要在列表中添加新数据。谢谢,您的建议奏效了。我认为它失败是因为引用了[index-1],但它失败是因为引用了[index]。我想当然地认为它会在列表中创建[index]元素。我猜这是在perl中发生的,而不是在Python中。@R.Wayne它认为它应该在创建数组对象时定义列表大小的语言中工作。但是在Python中(和其他一些语言一样),由于您不定义大小,并且大小是动态增加的,所以它不起作用。Perl必须属于前一类(PS:从未使用过Perl)