从另一个列表定义的列表中删除元素

时间:2013-11-16 02:58:01

标签: python

如何以此格式删除列表中的元素

a = [1,2,3,4,5]
b = [6,7,8,9,10]

c = b + a     # [6,7,8,9,10,1,2,3,4,5]

# c = c - b    expected output: [1,2,3,4,5]

2 个答案:

答案 0 :(得分:5)

使用list comprehension

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> c = b + a
>>> c
[6, 7, 8, 9, 10, 1, 2, 3, 4, 5]
>>> b = set(b)
>>> c = [x for x in c if x not in b]
>>> c
[1, 2, 3, 4, 5]
>>>

如果您需要set上的引用,请查看here

答案 1 :(得分:3)

如果b的长度非常大,可以使用b作为帮助您加快查找的集合

a, b = [1,2,3,4,5], [6,7,8,9,10]
c, b = a + b, set(b)
c = filter(lambda x: x not in b, c)
print c

<强>输出

[1, 2, 3, 4, 5]