从列表聚合多行

2024-05-13 18:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个列表中聚合多个值,以便在最终结果中不出现重复。你知道吗

我有这个密码:

import imdb
ia = imdb.IMDb()
top250 = ia.get_top250_movies()
i = 0;
for topmovie in top250:
    # First, retrieve the movie object using its ID
    movie = ia.get_movie(topmovie.movieID)
    # Print the movie's genres
    for genre in movie['genres']:
        cast = movie.get('cast')
        topActors = 2
        i = i+1;
        for actor in cast[:topActors]:
            if i <= 10:
                print('Movie: ', movie, ' Genre: ', genre, 'Actors: ', actor['name']);
            else:
                break;

我明白了:

Movie:  The Shawshank Redemption  Genre:  Drama Actors:  Tim Robbins
Movie:  The Shawshank Redemption  Genre:  Drama Actors:  Morgan Freeman
Movie:  The Godfather  Genre:  Crime Actors:  Marlon Brando
Movie:  The Godfather  Genre:  Crime Actors:  Al Pacino
Movie:  The Godfather  Genre:  Drama Actors:  Marlon Brando
Movie:  The Godfather  Genre:  Drama Actors:  Al Pacino
Movie:  The Godfather: Part II  Genre:  Crime Actors:  Al Pacino
Movie:  The Godfather: Part II  Genre:  Crime Actors:  Robert Duvall
Movie:  The Godfather: Part II  Genre:  Drama Actors:  Al Pacino
Movie:  The Godfather: Part II  Genre:  Drama Actors:  Robert Duvall
Movie:  The Dark Knight  Genre:  Action Actors:  Christian Bale
Movie:  The Dark Knight  Genre:  Action Actors:  Heath Ledger
Movie:  The Dark Knight  Genre:  Crime Actors:  Christian Bale
Movie:  The Dark Knight  Genre:  Crime Actors:  Heath Ledger
Movie:  The Dark Knight  Genre:  Drama Actors:  Christian Bale
Movie:  The Dark Knight  Genre:  Drama Actors:  Heath Ledger
Movie:  The Dark Knight  Genre:  Thriller Actors:  Christian Bale
Movie:  The Dark Knight  Genre:  Thriller Actors:  Heath Ledger
Movie:  12 Angry Men  Genre:  Crime Actors:  Martin Balsam
Movie:  12 Angry Men  Genre:  Crime Actors:  John Fiedler

有可能得到以下聚合吗?你知道吗

Movie:  The Shawshank Redemption  Genre:  Drama Actors:  Tim Robbins|Morgan Freeman
Movie:  The Godfather  Genre:  Crime|Drama  Actors:  Marlon Brando|Al Pacino|
Movie:  The Godfather: Part II  Genre:  Crime|Drama  Actors:  Al Pacino|Robert Duvall
Movie:  The Dark Knight  Genre:  Action|Crime|Drama|Thriller   Actors:  Christian Bale|Heath Ledger
Movie:  12 Angry Men  Genre:  Crime Actors:  Martin Balsam|John Fiedler

你能用列表得到这个吗?或者我需要将所有结果存储在一个数据帧中,然后使用groupby吗?你知道吗

谢谢!你知道吗


Tags: theactorsmovieiialdarkpartchristian
1条回答
网友
1楼 · 发布于 2024-05-13 18:28:58

尝试使用str.join公司()方法:

import imdb
ia = imdb.IMDb()
top250 = ia.get_top250_movies()
i = 0;
for topmovie in top250:
    # First, retrieve the movie object using its ID
    movie = ia.get_movie(topmovie.movieID)
    cast = movie.get('cast')
    topActors = 2
    i = i+1;
    actor_names= [actor['name'] for actor in cast[:topActors] ]
    if i <= 10:
         print('Movie: ', movie, ' Genre: ', '|'.join(movie['genres']), 'Actors: ', '|'.join(actor_names));
    else:
         break;

相关问题 更多 >