python查找两个列表之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22559627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python find difference between two lists
提问by K00764
I am new to programming but I keep learning, and recently I hit the wall so I'm asking for help. Sorry if this was discussed before, but I can't find answer to my problem. I have two lists. And I need to compare them, and in the result to get the objects that DON'T match.For example:
我是编程新手,但我一直在学习,最近我碰壁了,所以我寻求帮助。对不起,如果这之前讨论过,但我找不到我的问题的答案。我有两个清单。我需要比较它们,并在结果中得到不匹配的对象。例如:
a = [1,2,3,4,5,6]
b = [1,2,3,4,5,6,7,8,9]
result = [7,8,9].
And I only seem to find code and examples that return matches. Which I don't need.
而且我似乎只找到返回匹配项的代码和示例。我不需要的。
Lists are in file notepad file.txtfor you folks to keep in mind if you this helps you to help me. :)
列表在文件记事本 file.txt 中,如果您能帮助我,请记住。:)
采纳答案by user4815162342
You can convert the lists to sets and run the usual set operationssuch as difference or symmetric difference. For example, set(b) - set(a)evaluates to set([7, 8, 9]).
您可以将列表转换为集合并运行通常的集合操作,例如差分或对称差分。例如,set(b) - set(a)评估为set([7, 8, 9])。
回答by Dan Bechard
If the second set is not always a subset of the first then the difference operator '-' may not always return what you expect.
如果第二个集合并不总是第一个集合的子集,那么差异运算符“-”可能不会总是返回您期望的结果。
E.g.
例如
[1,2,3,4,5] - [3,4,5,6,7] = [1,2]
If you want a set of items in either list but not both lists use the symmetric difference operator '^'.
如果您想要一个列表中的一组项目但不是两个列表,请使用对称差异运算符“^”。
[1,2,3,4,5] ^ [3,4,5,6,7] = [1,2,6,7]
The symmetric difference operator, assuming it does what you want, also has the advantage of being commutative. This means you don't need to determine in which order to compare the sets like you do with the difference operator.
对称差分算子,假设它做你想要的,也有交换的优点。这意味着您不需要像使用差分运算符那样确定比较集合的顺序。

