Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从包含在另一个列表中的列表中除去外部元素_Python - Fatal编程技术网

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

Python 从包含在另一个列表中的列表中除去外部元素,python,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 my

我试图删除第二个列表中包含的列表的所有外部元素,同时保留那些可能被“夹”在其中的元素。我知道如何求两个集合的交集的补,但这里我只想删除所有的起始元素和尾随元素。到目前为止,我提出了以下建议,但感觉有些笨拙:

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

set(my_list)-set(nums)
?@sytech将删除重复项,这些重复项应该是@damores的可能重复项。lol,我正在处理完全相同的代码段,如果输入列表中的所有项都匹配到_remove list,则此操作将失败更改返回数据[idx[0]:idx[-1]+1]如果idx else[],那么就完美了
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]