目标
今天,我们正在学习使用Map或Dictionary数据结构的键值对映射。请查看教程选项卡中的学习材料和教学视频!
任务
给出姓名和电话号码,组装一本电话簿,将朋友的姓名映射到他们各自的电话号码。然后,您将得到一个未知的名称,以查询您的电话簿。对于被查询的每个条目,在表单name=phoneNumber中的新行上打印电话簿中的相关条目;如果找不到一个条目,则打印“未找到”。
注释:您的电话簿应该是字典/地图/哈希地图数据结构。
输入格式
第一行包含一个整数,表示电话簿中的条目数。后面的每一行都描述了单行上以空格分隔的值形式的条目。第一个值是朋友的名字,第二个值是-digit电话号码。
在电话簿条目行之后,有一个未知的查询行数。每一行(查询)都包含要查找的内容,您必须继续读取行,直到没有更多的输入为止。
注:名称由小写英文字母组成,仅限名。
输出格式
在每个查询的新行上,如果电话簿中没有相应的条目,则打印Not;否则,以name=phoneNumber格式打印全文和格式。
样本输入
3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry样本输出
sam=99912222
Not found
harry=12299933我的代码:
# No. of dictionary inputs
n = int(input())
# Code to fill the phonebook with entries
phonebook = {}
for _ in range(1, n+1):
entry = input().split(" ")
phonebook[entry[0]] = entry[1]
# Code for query intake
queries = []
while(1):
queries.append(input())
#need to figure out when the user stops input and need to break this loop then
if (input() == ""):
break
# Code for query result
for i in range(0, len(queries)):
if(queries[i] in phonebook):
print(queries[i] + "=" + phonebook[queries[i]])
# print(f"{queries[i]}={phonebook[queries[i]]}")
else:
print("Not found")我面临的问题:当我运行代码时,我把样例输入放在最后,但是,在输出结果时,查询“”没有得到输出。"edward“的期望输出将是”找不到“,但是,每一个偶数输入都会被遗漏,这可能是由于while循环中的if语句造成的。
发布于 2021-04-18 22:12:45
when (1):queries.append( out ())#需要确定用户何时停止输入并需要中断这个循环,然后如果( input () ==“):中断
应该只使用input()一次,然后使用append()或break
while True:
line = input()
if line == "":
break
queries.append(line)发布于 2021-04-19 08:08:19
我的最后一段代码起作用了,在我使用try以外块处理它时没有EOF错误:
# Code to fill the phonebook with entries
phonebook = dict() #Declare a dictionary
for _ in range(int(input())):
key, value = input().split()
phonebook[key] = value
#Trick - If there is no more input stop the program
try:
# Code for query intake
queries = []
while True:
line = input()
if line == "":
break
queries.append(line)
except Exception:
pass
# Code for query result
for i in range(0, len(queries)):
if(queries[i] in phonebook):
print(queries[i] + "=" + phonebook[queries[i]])
# print(f"{queries[i]}={phonebook[queries[i]]}")
else:
print("Not found")https://stackoverflow.com/questions/67153807
复制相似问题