从列表中删除子列表 [英] Removing a sublist from a list
问题描述
我有一个清单,例如l1 = [1,2,3,4]
和另一个列表:l2 = [1,2,3,4,5,6,7,1,2,3,4]
.
我想检查l1
是否是l2
中的子集,如果是,那么我想从l2
中删除这些元素,以使l2
变为[5,6,7,1,2,3,4]
,其中索引0-3已经删除.
I have a list e.g. l1 = [1,2,3,4]
and another list: l2 = [1,2,3,4,5,6,7,1,2,3,4]
.
I would like to check if l1
is a subset in l2
and if it is, then I want to delete these elements from l2
such that l2
would become [5,6,7,1,2,3,4]
, where indexes 0-3 have been removed.
是否有一种Python方式来做到这一点?
Is there a pythonic way of doing this?
我尝试过:
l1 = [1,2,3,4]
l2 = [1,2,3,4,5,6,7,1,2,3,4]
l3 = []
for i in l2:
if i in l1:
l3.append(i)
-> prints [5,6,7]
但是我希望输出是[5,6,7,1,2,3,4]
.
推荐答案
好吧,这是一种蛮力方式.可能有更有效的方法.如果您希望早日遇到匹配的子列表,则性能应该不会很糟糕.
Well, here is a brute-force way. There are probably more efficient ways. If you expect to encounter a matching sublist early, the performance shouldn't be terrible.
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> for i in range(0, len(l2), len(l1)):
... if l2[i:len(l1)] == l1:
... del l2[i:len(l1)]
... break
...
>>> l1
[1, 2, 3, 4]
>>> l2
[5, 6, 7, 1, 2, 3, 4]
>>>
或者如果您不想修改l2
,则可以执行以下操作:
Or if you don't want to modify l2
, you could do the following:
>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> for i in range(0, len(l2), len(l1)):
... if l2[i:len(l1)] == l1:
... break
...
>>> l2[:i] + l2[i+len(l1):]
[5, 6, 7, 1, 2, 3, 4]
>>>
这篇关于从列表中删除子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!