2016-11-14 82 views
2

我试图删除列表中包含的第二个列表中的所有外部元素,同时保留可能'夹在'里面的列表。我知道如何获得两组交集的补充,但是在这里我只想删除所有开始和结尾元素。到目前为止,我想出了下面,但感觉笨重:从列表中除去另一个列表中包含的外部元素

def strip_list(l, to_remove): 
    while l[0] in to_remove: 
     l.pop(0) 
    while l and l[-1] in to_remove: 
     l.pop(-1) 
    return l 

mylist = ['one', 'two', 'yellow', 'one', 'blue', 'three', 'four'] 
nums = ['one', 'two', 'three', 'four'] 
strip_list(mylist, nums) 
# > ['yellow', 'one', 'blue'] 
+0

'设置(my_list) - 设置(NUMS)'? – sytech

+1

@sytech将删除重复,应该留下 – Uriel

+2

可能重复[删除所有在另一个列表中发生的元素](http://stackoverflow.com/questions/4211209/remove-all-the-elements-那个发生在另一个列表中) – damores

回答

1
def strip_list(data, to_remove): 
    idx = [i for i, v in enumerate(data) if v not in to_remove] 
    return data[idx[0]:idx[-1]+1] 
+0

大声笑,我工作完全相同的一段代码,这将失败,如果输入列表中的所有项匹配内部to_remove列表 – Skycc

+1

更改返回数据返回[idx [0]:idx [-1] +1] if idx else [],那么应该是完美的 – Skycc