2017-01-27 6 views
0

Im Anschluss an eine vorherige Frage habe ich den folgenden Code. Aus irgendeinem Grund wird der Wert in der Liste nicht geändert, obwohl die currentlikes inkrementiert wurde. Die Kommentare erklären, was ich versuche zu tun:Wert in einer Liste ändern?

print("PRINT THE CURRENT FILM ROW", allfilms[3]) 
print("PRINT THE CURRENT LIKES", allfilms[3].split(",")[4]) 
currentlikes=allfilms[3].split(",")[4] #this retrieves the current likes from field 
print(currentlikes) 
currentlikes=+1 #this increments the current likes stored in the list 
print(currentlikes) 
allfilms[3].split(",")[4]=currentlikes #this attempts to change the value from 0 to 1 in the respective field 
print(allfilms)#this should print the updated list with the incremented +1 in the Third Row, Fourth Field (0 to 1) 

Die Ausgabe ist wie folgt. Es ändert, wie erwähnt, die aktuellen Likes, aber wenn wir am Ende allfilms drucken, wurde das entsprechende Feld nicht aktualisiert.

PRINT THE CURRENT FILM ROW 3,Sci-Fi,Star Trek, PG, 0 PRINT THE CURRENT LIKES 0 0 1 ['0,Genre, Title, Rating, Likes', '1,Sci-Fi,Out of the Silent Planet, PG, 0', '2,Sci-Fi,Solaris, PG,0', '3,Sci-Fi,Star Trek, PG, 0', '4,Sci-Fi,Cosmos, PG, 0', '5,Drama, The English Patient, 15, 0', '6,Drama, Benhur, PG, 0', '7,Drama, The Pursuit of Happiness, 12, 0', '8,Drama, The Thin Red Line, 18, 0', '9,Romance, When Harry met Sally, 12, 0', "10,Romance, You've got mail, 12, 0", '11,Romance, Last Tango in Paris, 18, 0', '12,Romance, Casablanca, 12, 0']

+5

'allfilms [3] .split (" ")' gibt eine neue Liste und Sie speichern diese Liste nicht überall –

+0

Der Rückgabewert von 'allfilms [3] .split (",")' hat keine dauerhafte Verbindung zu 'allfilms' oder' allfilms [3] '; Durch die Änderung wird 'allfilms 'nicht automatisch geändert. – user2357112

+3

Ist ** currentlikes = + 1 ** ein Tippfehler? –

Antwort

1

allfilms[3].split(",") teilt den gegebenen String und gibt eine neue Liste die keine Verbindung zum String hat.

Sie müssen der Liste beitreten und die Zeichenfolge unter allfilms[3] überschreiben.

>>> x = '3,Sci-Fi,Star Trek, PG, 0'; 
>>> record = x.split(',') 
>>> record[4] = 1 
>>> x 
'3,Sci-Fi,Star Trek, PG, 0' 
>>> record 
['3', 'Sci-Fi', 'Star Trek', ' PG', 1] 
>>> x = ','.join(str(i) for i in record) 
>>> x 
'3,Sci-Fi,Star Trek, PG,1' 
+0

Würde vorschlagen 'record [4] = int (record [4] .strip()) + 1 'als OP möchte das' like 'Feld erhöhen. –

Verwandte Themen