从列表中剥离另一个列表中包含的外部元素

时间:2016-11-14 15:04:13

标签: python

我正在尝试删除第二个列表中包含的列表的所有外部元素,同时保留可能被“夹在”内部的列表。我知道如何采用两组交集的补充,但在这里我只想删除所有开始和结尾元素。到目前为止,我已经提出了以下内容,但感觉很笨:

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

1 个答案:

答案 0 :(得分: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]