从Python的列表中排除项目

7

I have the next list of

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相同。如何实现这一点?

1
[element for i, element in enumerate(testList) if element not in m1] - Kamejoin
非常感谢!那个很好地运作了! - Chema Sarmiento
2
它过于复杂。 - Karoly Horvath
1
可能是从另一个列表中删除所有出现的元素的重复内容。 - skrrgwasme
3个回答

20
如果您不关心列表中的顺序,可以使用 集合 (sets) 来代替:
# result will be a set, not a list
not_in_testlist = set(testlist) - set(m1) 

如果您希望结果再次变成列表:

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

11
问题出在你使用了enumerate。变量i只会是一个整数,因此永远不会在仅包含列表的列表中。尝试使用以下代码:
[element for element in testList if element not in m1]

使用集合(Set)作为skrrgwasme建议的方式更加高效,因为它们在底层使用哈希。但是,您需要将元素定义为元组而不是列表,因为列表是不可哈希的(我想评论他的答案,但我没有足够的声望)。 - Andrew Allaire

4

请尝试以下方法:

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

这应该可以工作,但是它过于冗长。这种操作正是列表理解所专为之用。(http://www.secnetix.de/olli/Python/list_comprehensions.hawk) - skrrgwasme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接