在Python中查找列表之间不常见的项目

时间:2014-04-01 15:41:14

标签: python list-comprehension python-2.6

我在Python 2.6中有两个非常大的列表(比如50,000个字符串), a b

以下是两个选项。哪个更快,为什么?还有更好的方法吗?

c = [i for i in a if i not in b]

或者...

c = list(a)  # I need to preserve a for future use, so this makes a copy
for x in b:
    c.remove(x)

1 个答案:

答案 0 :(得分:5)

使用套装:

c = list(set(a).difference(b))

或者,如果订单很重要:

set_b = set(b)
c = [i for i in a if i not in set_b]