私は、ファイルから読み込まれた次のリストを持っている:films.txt
ではなく、文字よりも、リスト内の行の中のフィールドへのアクセス
['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']
私は特定のフィールド(すなわち"likes"
)にアクセスする必要がありますフィルムのインデックス番号に基づいて決定する。例えば
print("PRINT THE CURRENT FILM ROW", allfilms[3])
print("PRINT THE CURRENT LIKES", allfilms[4])
のための出力は、次のとおりです。
PRINT THE CURRENT FILM ROW 3,Sci-Fi,Star Trek, PG, 0
PRINT THE CURRENT LIKES 4,Sci-Fi,Cosmos, PG, 0
私はしかし、3行目に、0
でアクセスしたいどのような。これはインデックス番号に応じて3行目(または2行目)の4番目のフィールドなので、if
またはloop
が必要です。
私が試した:文字ではなく、フィールドを出力
print("PRINT THE CURRENT FILM ROW", allfilms[3][4])
を....
i
それは4番目の文字であるサイファイの「i」の文字を読んでいます...
前述のように、私は4番目のFIELD(0)が必要です。何かご意見は?
def likeafilm(x,username):
#prompt the user to enter the ID number they require
idnumber=int(input("To confirm, please enter the number of the film you wish to like:"))
#create a list which stores and displays all the data in the films txt file
with open("films.txt",mode="r") as f:
allfilms=[]
#allfilms=list(csv.reader(allfilms)) - this does not clean the extra spaces so try the next line
allfilms=[[x.strip() for x in row] for row in csv.reader(allfilms)]
print(allfilms[3])
allfilms[3][4]=str(int(allfilms[3][4])+1)
print(allfilms)
を、それは次のエラー生成します:
は、以下の提案に基づいて、私が試した
print(allfilms[3])
はIndexError:範囲
のうちリストインデックスまた、私がする必要が3の代わりにidnumberを使用します(上記の関数のように)
print(allfilms[idnumber])
同じエラー:
print(allfilms[idnumber])
IndexError: list index out of range
allfilms [3] .split( "、")[4])は '0'を生成します。ありがとうございます。しかし、問題は、値を変更する(値を増やす)ためにアクセスする必要があるということです。単なる印刷用ではありません。値を0から+1に変更するために使用するものを知っていますか(現在そのファイルに格納されているものに+1)。 –
私の編集を参照してください。戦略を少し変えるべきです。 –
私は試していました:currentlikes = allfilms [3] .split( "、")[4]#このフィールドから現在の好きなものを取得します。 print(currentlikes) currentlikes = + 1#リスト print(currentlikes) allfilms [3]。split( "、")[4] = currentlikes#それぞれのフィールドで値を0から1に変更しようとしました print(allfilms)#更新されたリストをインクリメントされた+1で3行目、 (0から1) *あなたの編集を通して読んでいただきます、ありがとうございます –