Das sieht so einfach aus, ich verstehe nicht, warum es nicht funktioniert.Zugriff auf vorheriges Element in einer Python-Liste
Dieser Code greift auf das vorherige Element in der Liste mit [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)
Dies ist nicht das vorherige Listenelement nicht zugreifen, obwohl es existiert, weil es gedruckt wird als line1[0]
aus.
# 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
Die Ausgabe lautet:
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
Es schlägt fehl, weil 'list [index]' beim ersten Mal nicht existiert. Sie müssen neue Daten an die Liste anhängen. – jszakmeister