从列表中删除子列表 [英] Removing a sublist from a list

查看:147
本文介绍了从列表中删除子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单,例如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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆