我有一个问题,是这样的的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