[英]How to fix code repetition and printing only the first line of file?
I am trying to read the file as dictionary and want to print out the outcomes that check whether the input(name) is in the file or not.我正在尝试将文件作为字典读取,并希望打印出检查输入(名称)是否在文件中的结果。 When I enter a name, it only prints the else statement although the name is in the file and prints the answer hundreds of times.
当我输入一个名称时,它只打印 else 语句,尽管名称在文件中并打印了数百次答案。 How can I not repeat the same answer over and over?
我怎么能不一遍又一遍地重复相同的答案? Can you please check my code?
你能检查我的代码吗?
d = {}
count = 0
for i in open("girlnames.txt", "r"):
(nameG, numberG) = i.split()
d[nameG] = numberG
count += 1
print(name, d[name])
if name in i:
print("{} is ranked {} in popularity among {} girl names.".format(name, count, d[name]))
else:
print("{} is not ranked among the top 1000 girl names.".format(name))
Assuming the file is in rank order:假设文件按等级排列:
d = {}
for i,line in enumerate(open("girlnames.txt", "r")):
nameG, numberG = line.split()
d[nameG] = (i+1, numberG)
print(name, d[name])
if name in d:
print("{} is ranked {} in popularity with {} names.".format(name, d[name][0], d[name][1])
else:
print("{} is not ranked among the top 1000 girl names.".format(name))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.