我已经成功地导入了文本文件并将其存储在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]]中的字符串] –
但你没有分配任何地方。对不起,我没有试图在无论如何粗鲁。检查我的答案是否有帮助。 –