Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.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_List - Fatal编程技术网

Python 从列表列表中排除项

Python 从列表列表中排除项,python,list,Python,List,我有下一张名单 testList = [] testList.append([0,-10]) testList.append([-12,122]) testList.append([13,172]) testList.append([17,296]) testList.append([-10,80]) testList.append([-16,230]) testList.append([-18, 296]) testList.append([-2, -8]) testList.append(

我有下一张名单

testList = []

testList.append([0,-10])
testList.append([-12,122])
testList.append([13,172])
testList.append([17,296])
testList.append([-10,80])
testList.append([-16,230])
testList.append([-18, 296])
testList.append([-2, -8])
testList.append([-5,10])
testList.append([2,-4])
另一个列表包含上一个列表中的元素:

m1 = []
m1.append([0, -10])
m1.append([13, 172])
然后,我尝试使用下一条语句从列表
testList
中获取子数组:

[element for i, element in enumerate(testList) if i not in m1]
但是我得到了与
testList
相同的列表


如何实现这一点?

问题在于使用enumerate。i将是一个整数,因此不会出现在一个只有列表的列表中。试试这个:

[element for element in testList if element not in m1]
试试这个:

def clean_list(my_list, exclusion_list):

    new_list = []
    for i in my_list:
        if i in exclusion_list:
            continue
        else:
            new_list.append(i)

    return new_list

如果您不关心列表中的顺序,可以使用:

如果希望结果再次成为列表:

 # result will be a list with a new order
not_in_m1 = list(set(testlist) - set(m1))
请注意,使用集合将丢失原始列表的顺序,因为集合是无序类型(它们在后台使用哈希)

如果您需要维护秩序,那么Andrew Allaire的回答是正确的:

# result is a list, order is preserved
not_in_testlist = [e for e in testlist if e not in m1] 

[元素为i,元素在枚举(testList)中,如果元素不在m1中]
非常感谢!那很好!这是不必要的复杂。这可能会重复,但不必要的冗长。这种类型的操作就是为之而设计的。使用skrrgwasme建议的集合要有效得多,因为它们在引擎盖下使用散列。但是,您需要元素是元组而不是列表,因为列表是不可散列的(我会对他的答案进行评论,但我缺乏这样做的声誉)。
# result is a list, order is preserved
not_in_testlist = [e for e in testlist if e not in m1]