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