所以我的问题是:
我想搜索字典,看看是否有任何键包含用户输入的关键字。例如,用户搜索John。
elif option == 3:
count = 0
found = None
search_key = input("What do you want to search for? ").lower()
for key, val in telephone_directory.items(): #takes each element in telephone directory
if search_key in key: #checks if it contains search_key
if found is None:
found = val
count = 1
if found is not None:
print(" ")
print("More than one match found. Please be more specific.")
print(" ")
count = 2
break
if found is None:
print("Sorry, " + str(search_key) + " was not found.")
print(" ")
function_options() #redirects back
if found is not None and count < 2:
print(str(search_key) + " was found in the directory.")
print("Here is the file on " + str(search_key) + ":")
print(str(search_key) + ":" + " " + telephone_directory[search_key])
print(" ")
function_options() #redirects back
所以我现在就在这里。不管搜索结果是什么,即使它是整个密钥,它也会返回“was not found”。我做错什么了?
您需要做出一些选择:允许多个匹配,只查找第一个匹配,或者最多只允许一个匹配。
要查找第一个匹配项,请使用
next()
:如果找不到匹配项,这将引发
StopIteration
;请返回默认值或捕获异常:这些版本只循环字典项,直到找到匹配项,然后停止;完整的
for
循环等价物为:注意
else
块;它只在for
循环被允许完成且未被break
语句中断时调用。要查找所有匹配键,可以使用列表理解:
最后,为了有效地只允许一个匹配,在同一个迭代器上使用两个
next()
调用,并在发现第二个匹配时引发错误:再次将其适应于
for
循环方法,仅当找到第二个项时才需要中断:您的版本不起作用,因为您为每个不匹配的键打印“未找到”。只有在遍历字典中的所有键之后,才能知道匹配键。
相关问题 更多 >
编程相关推荐