gpt4 book ai didi

用于搜索输入的 Python 搜索字典键

转载 作者:太空宇宙 更新时间:2023-11-04 03:58:07 25 4
gpt4 key购买 nike

所以这是我的问题:

我想搜索字典以查看是否有任何键包含用户输入的关键字。例如,用户搜索 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

这就是我现在的位置。无论搜索是什么,即使是整个键,它都会返回“未找到”。我做错了什么?

最佳答案

您需要做出一些选择;允许多个匹配项,仅查找第一个匹配项,或最多只允许一个匹配项。

要找到第一个匹配项,请使用 next():

match = next(val for key, val in telephone_directory.items() if search_key in key)

如果未找到匹配项,这将引发 StopIteration;返回默认值或捕获异常:

# Default to `None`
match = next((val for key, val in my_dict.items() if search_key in key), None)

try:
match = next(val for key, val in telephone_directory.items() if search_key in key)
except StopIteration:
print("Not found")

这些版本只会循环遍历字典项,直到找到匹配项,然后停止;完整的 for 循环等价物是:

for key, val in telephone_directory.items():
if search_key in key:
print("Found a match! {}".format(val))
break
else:
print("Nothing found")

注意 else block ;它仅在 for 循环允许完成且未被 break 语句中断时调用。

要查找所有 匹配键,可以使用列表理解:

matches = [val for key, val in telephone_directory.items() if search_key in key]

最后,为了高效地只允许一次匹配,在同一个迭代器上使用两次 next() 调用,并在找到第二个匹配时引发错误:

def find_one_match(d, search_key):
d = iter(d.items())
try:
match = next(val for key, val in d if search_key in key)
except StopIteration:
raise ValueError('Not found')

if next((val for key, val in d if search_key in key), None) is not None:
raise ValueError('More than one match')

return match

再次将其调整为 for 循环方法,将要求您仅在找到第二个项目时中断:

found = None
for key, val in telephone_directory.items():
if search_key in key:
if found is None:
found = val
else:
print("Found more than one match, please be more specific")
break
else:
if found is None:
print("Nothing found, please search again")
else:
print("Match found! {}".format(found))

您的版本不起作用,因为您为不匹配的每个键 打印“未找到”。直到最后遍历字典中的所有键时,您才知道没有匹配到键。

关于用于搜索输入的 Python 搜索字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17214664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com