Skip to main content
 首页 » 编程设计

python之从包含在另一个列表中的列表中去除外部元素

2025年04月02日9emanlee

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

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

请您参考如下方法:

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]