我試圖刪除列表中包含的第二個列表中的所有外部元素,同時保留可能'夾在'裏面的列表。我知道如何獲得兩組交集的補充,但是在這裏我只想刪除所有開始和結尾元素。到目前爲止,我想出了下面,但感覺笨重:從列表中除去另一個列表中包含的外部元素
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']
'設置(my_list) - 設置(NUMS)'? – sytech
@sytech將刪除重複,應該留下 – Uriel
可能重複[刪除所有在另一個列表中發生的元素](http://stackoverflow.com/questions/4211209/remove-all-the-elements-那個發生在另一個列表中) – damores