我正在研究一個程序,該程序需要一個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]
擁有所有的代碼在'嵌套的,如果__name__ ==「__main __」:'意味着,如果文件是由另一個腳本導入的,則它的功能都不可訪問。 – jDo