我是Python的新手,我需要一些关于字典功能的帮助。
我有一个演员和电影的文本文件,它看起来像这样:
Brad Pitt, Sleepers, Troy, Meet Joe Black, Oceans Eleven, Seven, Mr & Mrs Smith
Tom Hanks, You have got mail, Apollo 13, Sleepless in Seattle, Catch Me If You Can
Meg Ryan, You have got mail, Sleepless in Seattle
Diane Kruger, Troy, National Treasure
Dustin Hoffman, Sleepers, The Lost City
...
字典顺序是集合,电影是键,演员是值。
我的输入是一个演员姓名,我想查看他为谁演奏的合作演员所播放的电影。我该怎么检查呢?
我试着像:
actor = raw_input().lower()
coList = movieDict.keys()
coSet = set()
for keys in range(len(coList)):
for i in coList:
if actor == i:
continue
else:
coSet.add(actor)
print (', '.join(coSet()))
但它不起作用..
输出需要看起来像:
Brad Pitt
The actor's co-stars are:
Angelina Jolie, Anthony Hopkins, Diane Kruger, Dustin Hoffman, George Clooney, Julia Roberts, Kevin Bacon,
Morgan Freeman
答案 0 :(得分:1)
如果我明白你要做什么。查看{movie: set(actors)}
的字典,你想要一个演员的所有共同演员。我假设已经构建了movieDict
。
我不确定我理解你的外循环要做什么for keys in range(len(coList)):
似乎完全是多余的。
简化:
actor = input().lower() # raw_input() in Py2
coSet = set()
for movie, actors in movieDict.items():
if actor in actors:
coSet |= actors
print(', '.join(coSet))
此coSet
将包含原始actor
,但如果需要,可以只是remove
。
答案 1 :(得分:0)
如果你想搜索演员并观看他们所在的电影,似乎更好的方法是让演员成为键和电影的价值观。也就是说,我搜索
"Brad Pitt"
并取回他的价值观a.k.a. movies
"Sleepers, Troy, Meet Joe Black, Oceans Eleven, Seven, Mr & Mrs Smith"
假设您的输入文件与发布的摘录类似,并且您具有模式
'ACTOR', 'movie1', 'movie2', etc...
您可以逐行浏览文件并将每行视为列表的第一个索引,行[0]是Actor / Key。该行中的其他所有内容都作为单个列表传入,作为该键的值。
然后你也可以搜索特定的值并让它们返回键来找到联合星。
我认为这就是你要做的。这是正确的理解吗?如果您正在寻找代码,我很乐意将代码作为起点发布。
答案 2 :(得分:0)
随着您的数据库变大,您将希望避免迭代每部电影,希望找到您感兴趣的演员。
我会创建一个额外的dict
,您可以在其中查找演员以及查看电影的演员。因此filmography['Brad Pitt']
为您提供了他的电影列表,cast['Sleepers']
为您提供了该电影的演员列表。以下是如何做到的:
# The set-up:
filmography = {}
cast = {}
with open(filename, 'rt') as fh:
for line in fh:
line = line.strip()
if not line: continue
cells = line.split(',')
actor = cells[0].strip()
movies = [movie.strip() for movie in cells[1:]]
filmography.setdefault(actor,[]).extend(movies)
for movie in movies:
cast.setdefault(movie,[]).append(actor)
# The look-up:
def CoStars(actor):
return {costar for movie in filmography[actor] for costar in cast[movie] if costar is not actor}
# The test:
for actor in filmography:
print(actor + ' -> ' + ', '.join(CoStars(actor)))
打印:
Brad Pitt -> Dustin Hoffman, Diane Kruger
Tom Hanks -> Meg Ryan
Meg Ryan -> Tom Hanks
Dustin Hoffman -> Brad Pitt
Diane Kruger -> Brad Pitt
答案 3 :(得分:0)
This will find all of the movies the actor has been in and put that in the movies set and then iterate through that set of movies and create a set of actors in those moves. This set of actors represents every actor the given actor costared with. At the end the original actor is removed from the set of costars.
actor = raw_input().lower()
movies = set()
costars = set()
for key, value in movieDict.items():
if actor in value:
movies = movies.union(set([key]))
for movie in movies:
costars = costars.union(movieDict[movie])
costars = costars.difference(set([actor]))