简体   繁体   English

从列表中删除子列表

[英]Removing a sublist from a list

I have a list eg l1 = [1,2,3,4] and another list: l2 = [1,2,3,4,5,6,7,1,2,3,4] . 我有一个列表,例如l1 = [1,2,3,4]和另一个列表: 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. 我想检查l1是否是l2的子集,如果是,那么我想从l2删除这些元素,以使l2成为[5,6,7,1,2,3,4] ,其中索引为0 -3已被删除。

Is there a pythonic way of doing this? 有pythonic的方法吗?

I tried 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]

However I would like the output to be [5,6,7,1,2,3,4] . 但是我希望输出为[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]
>>>

Or if you don't want to modify l2 , you could do the following: 或者,如果您不想修改l2 ,则可以执行以下操作:

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

I'm not proud of this, and it's not pythonic, but I thought it might be a bit of fun to write. 我对此并不感到骄傲,也不是pythonic,但我认为编写它可能会有点有趣。 I've annotated the code to make it a little more obvious what's happening. 我已经注释了代码,使事情变得更加明显。

>>> import re
>>> from ast import literal_eval

>>> l1 = [1,2,3,4]
>>> l2 = [1,2,3,4,5,6,7,1,2,3,4]
>>> literal_eval(         # convert the string into a python collection
...    re.sub(            # use a regex as a replacement
...       str(l1)[1:-1],  # string of the list, without surrounding brackets
...       '',             # replace with empty
...       str(l2)[1:-1],  # string for replacement, again without brackets
...       count=1         # only replace the first match
...    ).strip(',')       # replace any preceeding or trailing commas
...     .strip()          # replace any preceeding or trailing whitespace
... )
(5, 6, 7, 1, 2, 3, 4)

The output here is a tuple, but you could wrap it in list() if that's what you really want. 这里的输出是一个元组,但是如果您真正想要的是,可以将其包装在list() Again, I'm not proud of this, but it works at least for this simple case. 同样,我对此并不感到骄傲,但至少在这种简单情况下,它可以工作。 Juanpa's solution is much more preferable to this. Juanpa的解决方案对此更为可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM