继上一个问题后,我有以下代码。出于某种原因,尽管currentlikes
已递增,但列表中的值未更改。评论解释了我试图做的事情:
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)
输出如下。如上所述,它会更改当前的喜欢,但是当我们在结尾处打印allfilms
时,相关字段尚未更新。
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']
答案 0 :(得分:1)
allfilms[3].split(",")
拆分给定字符串并返回没有与字符串连接的新列表。
您需要加入列表并在allfilms[3]
覆盖字符串。
>>> 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'