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

2024-10-03 09:08:49 发布

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

我在一个列表中有一个列表,我想在遇到其中一个元素中的值之前删除某些元素。举例如下:

输入:

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

输出:

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

应删除包含“name”的元素之前的所有元素


Tags: namepos元素列表outputbannerabcqwerty
1条回答
网友
1楼 · 发布于 2024-10-03 09:08:49

这可以使用^{}来完成,它在某些条件停止为真后给出序列中的元素

将其应用于您的示例:

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

相关问题 更多 >