我想制作一個搜索程式,但我堅持使用特定的演算法。首先,我會從用戶那里得到任何單詞然后檢查用戶的單詞是否包含在 di 值的任何關鍵字中。如果包含用戶的話,則回傳鍵值作為串列型別。如果不包括用戶的話,則執行程式。
例如,如果我輸入“nice guy”,那么函式應該回傳“matthew”作為串列型別。
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(*dicts):
list_check = []
search = input("Enter word for search: ")
for dic in dicts:
if search in dic[word]:
list_check.append(keyword)
else:
print("None")
break
print(searchWords(dic_1))
我一直堅持接近演算法......我希望你們給我任何建議或想法來制作這個演算法。
uj5u.com熱心網友回復:
您可以嘗試如下使用串列推導來提取匹配的鍵:
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(dictex):
search = input("Enter word for search: ")
return [k for k,v in dictex.items() if search in v]
print(searchWords(dic_1))
輸出:
Enter word for search: nice guy
['matthew']
另一個輸出:
Enter word for search: guy
['matthew', 'dennis', 'alex']
uj5u.com熱心網友回復:
簡單的方法是
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(*dicts):
lst = []
t = input('Write something to search:')
for dict_ in dicts:
for k,v in dict_.items():
if t in v:
lst =[k]
return lst
使用串列理解。
def searchWords(*dicts):
t = input('Write something to search:')
lst = [k for dict_ in dicts for k,v in dict_.items() if t in v]
return lst
uj5u.com熱心網友回復:
正如我在評論中提到的那樣,這應該可以完成作業。
dic_1 = {'matthew':'he is a nice guy', 'dennis':'he is a bad guy', 'alex':'he is a good guy'}
dic_2 = {'manchester': 'city from england', 'tokyo':'city from japan', 'rome':'city from italy'}
def searchWords(*dicts):
list_check = []
search = input("Enter word for search: ")
for dict in dicts:
for key in dict:
if search in dict[key]:
list_check.append({key:dict[key]})
uj5u.com熱心網友回復:
理解
首先,您可以使用ChainMap合并您的字典
from collections import ChainMap
chain = ChainMap(*dicts)
然后您可以使用串列推導進行搜索以獲得更好的性能
results = [v for v in chain.values() if 'keyword' in v]
篩選
您也可以使用 python過濾器功能
newDict = dict(filter(lambda elem: 'keyword' in elem[1], chain.items()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/471198.html
下一篇:如何找到與特定頂點相關的邊串列
