Python组列表元素按值分成元组

时间:2019-02-20 22:42:07

标签: python list tuples grouping

我有此列表:

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')]

2 个答案:

答案 0 :(得分:5)

这是经典的use case for itertools.groupby

from itertools import groupby

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

这会将您的输入分组为*和非*的运行,丢弃*组,而tuple将非*

答案 1 :(得分:3)

使用itertools.groupby根据条目是否为*对条目进行分组,然后使用*(不相等)方法或使用__ne__保留不属于lambda的部分。等效的>>> import itertools >>> mylist = ['*', 'Drama', 'Film Noir', 'Mystery', 'Romance', '*', 'Dance', 'Drama', 'Musical', '*', 'Crime', 'Drama', '*', 'Action', 'Drama', 'Period', 'Western', '*', 'Adaptation', 'Based-on', 'Comedy', 'Romance', '*', 'Mystery', 'Thriller', '*', 'Comedy'] >>> [tuple(g) for k, g in itertools.groupby(mylist, key="*".__ne__) if k] [('Drama', 'Film Noir', 'Mystery', 'Romance'), ('Dance', 'Drama', 'Musical'), ('Crime', 'Drama'), ('Action', 'Drama', 'Period', 'Western'), ('Adaptation', 'Based-on', 'Comedy', 'Romance'), ('Mystery', 'Thriller'), ('Comedy',)] 表达式:

<a class="nav-link" href="#">
   <i class="fas fa-user fa-2x" style="vertical-align: middle;"></i>Вход
   <!-- Here you set the other label in the same link -->
   <span>Регистрация</span>
</a>