这里有一段较短的 Pythonic 代码,notebook 可以访问here。
Python 提供了一些更简洁的方式来理解我们的代码。在这个脚本中,我使用了两种这样的技术。
技术 1:列表理解
列表推导式只不过是循环遍历一个可迭代对象并生成一个列表作为输出。在这里,我们也可以包括计算和条件。另一种技术,即Technique-2:字典理解,与此非常相似,您可以阅读它here。
例如没有列表理解的代码
numbers = []
for i in range(10):
numbers.append(i)
print(numbers)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
使用列表理解的代码
numbers = [i for i in range(10)]
print(numbers)
#Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
来到 OPs 问题,get_top250_movies() 函数返回一个包含很少细节的电影列表。可以像这样检查它返回的确切参数。从输出中可以看出,电影详细信息不包含流派和其他详细信息。
from imdb import IMDb
ia = IMDb()
top250Movies = ia.get_top250_movies()
top250Movies[0].items()
#output:
[('rating', 9.2),
('title', 'The Shawshank Redemption'),
('year', 1994),
('votes', 2222548),
('top 250 rank', 1),
('kind', 'movie'),
('canonical title', 'Shawshank Redemption, The'),
('long imdb title', 'The Shawshank Redemption (1994)'),
('long imdb canonical title', 'Shawshank Redemption, The (1994)'),
('smart canonical title', 'Shawshank Redemption, The'),
('smart long imdb canonical title', 'Shawshank Redemption, The (1994)')]
但是,get_movie() 函数返回更多关于电影的信息,包括Genres。
我们结合这两个函数来获得前 20 部电影的类型。首先,我们调用 get_top250_movies(),它返回包含较少详细信息的前 250 部电影的列表(我们只对获取 movieID 感兴趣)。然后我们为顶级电影列表中的每个电影 ID 调用 get_movie(),这将返回我们的流派。
程序:
from imdb import IMDb
#initialize and get top 250 movies; this list of movies returned only has
#fewer details and doesn't have genres
ia = IMDb()
top250Movies = ia.get_top250_movies()
#TECHNIQUE-1: List comprehension
#get top 20 Movies this way which returns lot of details including genres
top20Movies = [ia.get_movie(movie.movieID) for movie in top250Movies[:20]]
#TECHNIQUE-2: Dictionary comprehension
#expected output as a dictionary of movie titles: movie genres
{movie['title']:movie['genres'] for movie in top20Movies}
输出:
{'12 Angry Men': ['Drama'],
'Fight Club': ['Drama'],
'Forrest Gump': ['Drama', 'Romance'],
'Goodfellas': ['Biography', 'Crime', 'Drama'],
'Inception': ['Action', 'Adventure', 'Sci-Fi', 'Thriller'],
"One Flew Over the Cuckoo's Nest": ['Drama'],
'Pulp Fiction': ['Crime', 'Drama'],
"Schindler's List": ['Biography', 'Drama', 'History'],
'Se7en': ['Crime', 'Drama', 'Mystery', 'Thriller'],
'Seven Samurai': ['Action', 'Adventure', 'Drama'],
'Star Wars: Episode V - The Empire Strikes Back': ['Action',
'Adventure',
'Fantasy',
'Sci-Fi'],
'The Dark Knight': ['Action', 'Crime', 'Drama', 'Thriller'],
'The Godfather': ['Crime', 'Drama'],
'The Godfather: Part II': ['Crime', 'Drama'],
'The Good, the Bad and the Ugly': ['Western'],
'The Lord of the Rings: The Fellowship of the Ring': ['Action',
'Adventure',
'Drama',
'Fantasy'],
'The Lord of the Rings: The Return of the King': ['Adventure',
'Drama',
'Fantasy'],
'The Lord of the Rings: The Two Towers': ['Adventure', 'Drama', 'Fantasy'],
'The Matrix': ['Action', 'Sci-Fi'],
'The Shawshank Redemption': ['Drama']}