问题描述
我有两个列表:
big_list = [2, 1, 2, 3, 1, 2, 4]
sub_list = [1, 2]
我要删除big_list中所有出现的sub_list.
I want to remove all sub_list occurrences in big_list.
结果应为[2, 3, 4]
对于字符串,您可以使用以下代码:
For strings you could use this:
'2123124'.replace('12', '')
但是AFAIK不适用于列表.
But AFAIK this does not work for lists.
这不是从列表中删除子列表的重复项,因为我想从大列表中删除所有子列表.在另一个问题中,结果应为[5,6,7,1,2,3,4]
.
This is not a duplicate of Removing a sublist from a list since I want to remove all sub-lists from the big-list. In the other question the result should be [5,6,7,1,2,3,4]
.
更新:为简单起见,在此示例中,我采用了整数.但是列表项可以是任意对象.
Update: For simplicity I took integers in this example. But list items could be arbitrary objects.
Update2:
如果big_list = [1, 2, 1, 2, 1]
和sub_list = [1, 2, 1]
,我希望结果为[2, 1]
(如'12121'.replace('121', '')
)
if big_list = [1, 2, 1, 2, 1]
and sub_list = [1, 2, 1]
,I want the result to be [2, 1]
(like '12121'.replace('121', '')
)
Update3:
我不喜欢将StackOverflow中的源代码复制粘贴到我的代码中.这就是为什么我在软件建议中提出了第二个问题:
I don't like copy+pasting source code from StackOverflow into my code. That's why I created second question at software-recommendations: https://softwarerecs.stackexchange.com/questions/51273/library-to-remove-every-occurrence-of-sub-list-from-list-python
Update4:如果您知道要进行此方法调用的库,请将其编写为答案,因为这是我的首选解决方案.
Update4: if you know a library to make this one method call, please write it as answer, since this is my preferred solution.
测试应通过此测试:
def test_remove_sub_list(self):
self.assertEqual([1, 2, 3], remove_sub_list([1, 2, 3], []))
self.assertEqual([1, 2, 3], remove_sub_list([1, 2, 3], [4]))
self.assertEqual([1, 3], remove_sub_list([1, 2, 3], [2]))
self.assertEqual([1, 2], remove_sub_list([1, 1, 2, 2], [1, 2]))
self.assertEquals([2, 1], remove_sub_list([1, 2, 1, 2, 1], [1, 2, 1]))
self.assertEqual([], remove_sub_list([1, 2, 1, 2, 1, 2], [1, 2]))
推荐答案
您必须自己实现它.这是基本思想:
You'd have to implement it yourself. Here is the basic idea:
def remove_sublist(lst, sub):
i = 0
out = []
while i < len(lst):
if lst[i:i+len(sub)] == sub:
i += len(sub)
else:
out.append(lst[i])
i += 1
return out
这将遍历原始列表的每个元素,并将其添加到输出列表(如果它不是子集的成员).这个版本的效率不是很高,但它的工作方式类似于您提供的字符串示例,因为它创建了一个不包含您的子集的新列表.只要它们支持==
,它也适用于任意元素类型.从[1,1,1,1]
中删除[1,1,1]
会正确生成[1]
,就像字符串一样.
This steps along every element of the original list and adds it to an output list if it isn't a member of the subset. This version is not very efficient, but it works like the string example you provided, in the sense that it creates a new list not containing your subset. It also works for arbitrary element types as long as they support ==
. Removing [1,1,1]
from [1,1,1,1]
will correctly result in [1]
, as for a string.
这是一个 IDEOne链接,展示了
>>> remove_sublist([1, 'a', int, 3, float, 'a', int, 5], ['a', int])
[1, 3, <class 'float'>, 5]
这篇关于如何从列表中删除每次出现的子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!