我已經成功地導入了文本文件並將其存儲在dictionary.i希望能夠要求用戶輸入他想要的數字並打印值與用戶想要的數字相對應。例如該文件包含2個名字1:chris 2:sam ...我想讓程序詢問用戶輸入,用戶輸入2,它應該打印字典中的sam。python-當用戶要求輸入時從文件打印
這裏是我的代碼:
file = open("songranks.txt","r")
d={}
#Repeat for each song in the text file
for line in file:
#Let's split the line into an array called "fields" using the "," as a separator:
fields = line.split(",")
#and let's extract the data:
songrank = fields[0]
list =[fields[1],fields[2]]
k = [str(x) for x in list]
["".join(k)]
chris=len(k)-1
k=k[0:chris]
d[songrank]=k
#It is good practice to close the file at the end to free up resources
file.close()
任何幫助,將不勝感激。
這行是什麼?[「」.join(k)]'在幹什麼? –
我沒有複製代碼和yea [「」.join(k)]應該加入列表= [字段[1],字段[2]]中的字符串] –
但你沒有分配任何地方。對不起,我沒有試圖在無論如何粗魯。檢查我的答案是否有幫助。 –