获取两个列表之间的差异

新手上路,请多包涵

我在 Python 中有两个列表:

 temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']

我想创建第三个列表,其中包含第一个列表中不在第二个列表中的项目:

 temp3 = ['Three', 'Four']

有没有没有循环和检查的快速方法?

原文由 Max Frai 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 519
2 个回答

要获取 temp1 但不在 temp2 中的元素:

 In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']

注意它是不对称的:

 In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1])

您可能期望/希望它等于 set([1, 3]) 的地方。如果您确实想要 set([1, 3]) 作为您的答案,您可以使用 set([1, 2]).symmetric_difference(set([2, 3]))

原文由 ars 发布,翻译遵循 CC BY-SA 4.0 许可协议

现有的解决方案都提供以下其中之一:

  • 比 O(n*m) 性能更快。
  • 保留输入列表的顺序。

但到目前为止,还没有解决方案兼具两者。如果你想要两者,试试这个:

 s = set(temp2)
temp3 = [x for x in temp1 if x not in s]

性能测试

import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)

结果:

 4.34620224079 # ars' answer
4.2770634955  # This answer
30.7715615392 # matt b's answer

我提出的方法以及保留顺序也比集合减法(稍微)快,因为它不需要构造不必要的集合。如果第一个列表比第二个列表长得多并且散列计算成本很高,则性能差异会更加明显。这是证明这一点的第二个测试:

 init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''

结果:

 11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer

原文由 Mark Byers 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题