我有这个清单:

mylist = ['*', 'Drama', 'Film Noir', 'Mystery', 'Romance', '*', 'Dance', 'Drama', 'Musical', '*', 'Crime', 'Drama', '*', 'Action', 'Drama', 'Period', 'Western', '*', 'Adaptation', 'Based-on', 'Comedy', 'Romance', '*', 'Mystery', 'Thriller', '*', 'Comedy']


显然,元素“ *”将列表中的组分隔开。如何在'*'之间对元素的出现进行分组?所需的结果将如下所示:

expected_list = [('Drama', 'Film Noir', 'Mystery', 'Romance'), ('Dance', 'Drama', 'Musical'), ('Crime', 'Drama'), ('Action', 'Drama', 'Period', 'Western'), ('Adaptation', 'Based-on', 'Comedy', 'Romance'), ('Mystery', 'Thriller'), ('Comedy')]

最佳答案

这是经典的use case for itertools.groupby

from itertools import groupby

expected_list = [tuple(grp) for isstar, grp in groupby(mylist, key='*'.__eq__) if not isstar]


这会将您的输入分组为*和not- *的运行,删除*组,并且tuple向上列出非*组。

10-06 00:03