我正在嘗試制作搜索程式,但我陷入了一些回圈部分。函式作業有幾個步驟。首先,我會從用戶那里得到一個詞(輸入)。然后,我將比較用戶的輸入是否包含在任何字典中的任何值中如果包含用戶的輸入,那么我想將字典中的鍵值列印為串列型別。如果沒有,那么我想執行回圈并列印出一些訊息。
例如,如果我輸入 nice 作為輸入,那么程式應該將 matthew 列印為串列型別。程式應該保持回圈,直到我輸入不包含在字典值中的輸入。例如,如果我從 dic_1 和 dic_2 鍵入任何輸入,則程式應保持回圈,直到我輸入不包含在字典值中的輸入。
如果我輸入垃圾或字典中沒有的東西,那么程式應該列印出不匹配的訊息。
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):
while(True):
list_1 = []
t = input('Enter a word for search:')
for dic in dicts:
for k,v in dic.items():
if t in v:
list_1 =[k]
else:
print("Nothing match, end program")
break
return list_1
print(searchWords(dic_1, dic_2)
現在,當我輸入一次時列印出鍵值沒有問題,但我卡在回圈部分。我想在程式中保持回圈,直到我輸入不涉及字典值的單詞,但我無法找出解決回圈問題的任何演算法。我嘗試了 for 回圈和 if 回圈,但我失敗了。因此,如果你們可以為回圈提供任何建議或想法,將不勝感激。
uj5u.com熱心網友回復:
處理此問題的最簡單方法是使用 True/False 標志,如下所示:
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):
while True:
t = input('Enter a word for search: ')
found = []
for dic in dicts:
for k, v in dic.items():
if t in v.split():
found.append(k)
if not found:
print('No match')
break
else:
print(*found)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471971.html
