我有一個問題,是這樣的的Python:該功能可通過詞典的詞典搜索
寫一個函數findActor,需要一個電影片名和角色的名字和回報的合同,文檔字符串和實施在給定的電影中扮演給定角色的演員/女演員。如果沒有找到指定的電影或給定的字符,它打印出錯誤消息,並返回一個空字符串
我已經做了以下的功能,這將有所幫助這樣做。而myIMDb是一個全球詞典,設置爲空dic開始
def addMovie (title, charList, actList):
"""The function addMovie takes a title of the movie, a list of characters,
and a list of actors. (The order of characters and actors match one
another.) The function addMovie adds a pair to myIMDb. The key is the title
of the movie while the value is a dictionary that matches characters to
actors"""
dict2 = {}
for i in range (0, len(charList)):
dict2 [charList[i]] = actList[i]
myIMDb[len(myIMDb)] = {title: dict2}
return myIMDb
def listMovies():
"""returns a list of titles of all the movies in the global variable myIMDb"""
titles = []
for i in range (len(myIMDb)):
titles.append((list(myIMDb[i].keys())))
return titles
這裏是我遇到問題的地方。當我想編寫findActor函數時,我無法返回。我沒有完成這個功能,但我在想我已經做了一些根本性的錯誤。我感覺自己走錯了路,而我寫得越多越失去越多。這就是我的目的。任何有關如何糾正這艘沉船的建議將不勝感激。
def findActor(title, name):
myIMDb = {}
for i in range (len(myIMDb)):
if title == myIMDb[i].keys():
if name == myIMDb[i].get(name):
return myIMDb[i].get(name)
else:
return "Error: No Movie found"
我正在填充myIMDb,我只是忘了說我是。我也做了你的建議。它拋棄了我的「listMovies」函數,而且我仍然使用findActor獲得相同的概率。無論我在參數中輸入什麼,它都不會返回任何內容。 – Jonerhan
嗯,通過不返回任何你的意思它只是不返回任何東西或它返回錯誤?在您的原始代碼中,由於您還將'myIMDb'本地初始化爲一個空字典,因此您只需循環執行即可,因爲字典中沒有任何內容。確保你使用的是全局myIMDb,而不是你本地的空白。 – Penguinator
沒關係,我明白了,這只是我自己的一個愚蠢的標籤錯誤。謝謝你的幫助! – Jonerhan