Python - 使用“set”查找列表中的不同项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15455737/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:11:06  来源:igfitidea点击:

Python - Use 'set' to find the different items in list

pythoncompare

提问by RPiAwesomeness

I need to compare two lists in Python, and I know about using the setcommand to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?

我需要在 Python 中比较两个列表,并且我知道如何使用该set命令来查找相似的项目,但是是否可以使用另一个命令来自动比较它们,而不必为其编写代码?

I would like to find the items that aren't in each one. Say list one is as follows:

我想找到每个项目中没有的项目。说清单一如下:

[1, 2, 3, 4, 5, 6] 

and list two is:

清单二是:

[1, 2, 3, 4, 6]

I want to find that 5is missing from the list, hopefully by a command, but I do know how to loop through comparing.

我想5从列表中找到它,希望通过命令,但我知道如何循环比较。

采纳答案by tifon

Looks like you need symmetric difference:

看起来你需要对称差异:

a = [1,2,3]
b = [3,4,5]

print(set(a)^set(b))


>>> [1,2,4,5]

回答by Seth

The docsare a good place to start. Here are a couple examples that might help you determine how you want to compare your sets.

文档是一个良好的开端。以下是一些示例,可以帮助您确定要如何比较您的集合。

To find the intersection (items that are in both sets):

要找到交集(两个集合中的项目):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a & b
set([4, 5, 6])

To find the difference (items that only in one set):

找出差异(仅在一组中的项目):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a - b
set([1, 2, 3])
>>> b - a
set([7, 8, 9])

To find the symmetric difference (items that are in one or the other, but not both):

要找到对称差异(在一个或另一个中的项目,但不是两个):

>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a ^ b
set([1, 2, 3, 7, 8, 9])

Hope that helps.

希望有帮助。

回答by Fredrik Pihl

A simple list comprehension

一个简单的列表理解

In [1]: a=[1, 2, 3, 4, 5, 6] 

In [2]: b=[1, 2, 3, 4, 6]

In [3]: [i for i in a if i not in b]
Out[3]: [5]