2016-11-14 80 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