我有此列表:
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')]
答案 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>