我正在开发一个程序,它接收imdb文本文件,并根据用户输入N输出顶级演员(按电影外观)
然而,我遇到了一个问题,在同样数量的电影中,演员占据了我的位置,这是我需要避免的。相反,如果两个演员在5部电影中,例如,数字5应该出现,演员的名字应该合并,用分号隔开。你知道吗
我已经尝试了多种解决方法,但没有任何效果。有什么建议吗?你知道吗
if __name__ == "__main__":
imdb_file = raw_input("Enter the name of the IMDB file ==> ").strip()
print imdb_file
N= input('Enter the number of top individuals ==> ')
print N
actors_to_movies = {}
for line in open(imdb_file):
words = line.strip().split('|')
actor = words[0].strip()
movie = words[1].strip()
if not actor in actors_to_movies:
actors_to_movies[actor] = set()
actors_to_movies[actor].add(movie)
movie_list= sorted(list(actors_to_movies[actor]))
#Arranges Dictionary into List of Tuples#
D = [ (x, actors_to_movies[x]) for x in actors_to_movies]
descending = sorted(D, key = lambda x: len(x[1]), reverse=True)
#Prints Tuples in Descending Order N number of times (User Input)#
for i in range(N):
print str(len(descending[i][1]))+':', descending[i][0]
有一个有用的方法itertools.groupby
它允许您按某个键将列表拆分为多个组。使用它,您可以很容易地编写一个打印顶级角色的函数:
用法和示例:
相关问题 更多 >
编程相关推荐