从列表中删除多个元素,直到遇到一个值

问题描述 投票:-3回答:2

我在列表中有一个列表,我想删除某些元素,然后再遇到其中一个元素的值。下面给出示例:

输入:

A = [[abc], [qwe], [zxc], [asd], [name, qwe, qqwe,pos],[qwerty,lkasd, banner, kostop]] ...

输出:

Output = [[name, qwe,qqwe,pos], [qwerty,lkasd, banner, kostop]] …

应该删除包含“名称”的元素之前的所有元素。

python python-3.x
2个回答
2
投票

这可以使用itertools.dropwhile完成,在某些条件停止成立后,它会从序列中提供元素。

将其应用于您的示例:

itertools.dropwhile

0
投票

我不知道这是否算作虐待动物...

>>> a = [['abc'], ['qwe'], ['zxc'], ['asd'], ['name', 'qwe', 'qqwe', 'pos'], ['qwerty', 'lkasd', 'banner', 'kostop']]
>>> from itertools import dropwhile
>>> list(dropwhile(lambda x: 'name' not in x, a))
[['name', 'qwe', 'qqwe', 'pos'], ['qwerty', 'lkasd', 'banner', 'kostop']]
© www.soinside.com 2019 - 2024. All rights reserved.