黑客第8天:字典和地图问题(使用Python)



目标
今天,我们将学习使用Map或Dictionary数据结构的键值对映射。查看"教程"选项卡中的学习材料和教学视频!

任务
给定姓名和电话号码,组装一本电话簿,将朋友的姓名映射到他们各自的电话号码。然后,你会得到一个未知数量的名字来查询你的电话簿。对于每个查询,将电话簿中的相关条目打印在新的行上,格式为name=phoneNumber;如果找不到的条目,请改为打印"未找到"。

注意:您的电话簿应该是Dictionary/Map/HashMap数据结构

输入格式
第一行包含一个整数,表示通讯录中的条目数。随后的每一行都以单行上空格分隔值的形式描述一个条目。第一个值是朋友的名字,第二个值是一个-位的电话号码
在电话簿条目的行之后,有未知数量的查询行。每一行(查询(都包含一个要查找的行,您必须继续读取行,直到没有更多输入为止。

注意:名称由小写英文字母组成,仅为名字

输出格式
如果姓名在通讯录中没有对应的条目,则在每个查询的新行上打印"未找到";否则,请打印完整的,格式为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")

我面临的问题:当我运行代码时,我输入了样本,一切都很好,直到最后,然而,在打印出结果时,查询"爱德华;没有得到输出。对于";爱德华;将是";未找到";然而,每一个偶数输入都会被遗漏,这可能是由于while循环中的if语句造成的。

while(1):
queries.append(input())
#need to figure out when the user stops input and need to break this loop then
if (input() == ""):
break

应仅使用input()一次,然后使用append()break:

while True:
line = input()
if line == "":
break
queries.append(line)

我的最终代码有效,没有EOF错误,因为我使用try-except块处理它:

# 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")

最新更新