在上周的文章中,你已经了解了 Python set difference() 的全部内容。现在我们将探索另一个常用的 set(集合)函数。Python 集合交集允许在两个多个集合之间查找公共元素。它有很多有用的应用,例如在求职者数据之间寻找相同技能。

今天你将学习关于 Python set intersection 的所有知识,读完这篇文章后,你就可以自信地使用它了。

这里原作者放了一个录制的讲解视频,由于是 youtube 的,有条件的同学可以自行观看。

https://www.youtube.com/watch?v=Jhs-tXUD3bs

Python set 交集基础

什么是Python集合交集?这就是我们将在本节中回答的问题。通过可视化示例,你将完全理解定义、语法和返回值。

定义和用法

set intersection 函数返回两个或多个集合的公共元素。例如,我喜欢用Python、JavaScript和PHP编写代码,你喜欢用Java、Python和Ruby。我们都同时喜欢Python 。我们将在整篇文章中使用这两个集合,这样只是为了保持简单,当更多集合相交时,同样的逻辑也适用。

请看以下两组:

Image 1 – Two sets with programming languages (image by author)

Calculating an intersection between these sets means we’ll get a new set with a single element – Python. Why? Because it’s the only element common to both sets:

计算这些集合之间的交集,意味着我们将得到一个包含单个元素的新集合 – Python。为什么?因为它是两个集合中唯一相同的元素。

Image 2 – Set intersection in action (image by author)

The set intersection in Python is commonly represented with a Venn diagram. Here’s what it looks like:

集合的交集通常用韦恩图表示:

Image 3 – Set intersection as a Venn diagram (image by author)

Only Python is common to both sets, so I’ve highlighted the intersection area in blue.

What does intersection method do in Python and how do you find the intersection between sets? Let’s go over the syntax to answer these questions.

上述两个集合的通用部分是 Python,用蓝色显示交集区域。

在 Python 中 intersection 方法是做什么的? 如何找到集合之间的交集?让我们回答这些问题。

# 两个集合的交集
set1.intersection(set2)

# 多个集合的交集
set1.intersection(set2, set3)

参数说明:

  • set1:必需,要查找相同元素的集合
  • set2set3 : 可选,其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

返回值:
Intersection() 函数返回一个新的集合,它是第一个集合和其他集合之间的交集,但是只有在集合或迭代对象传递给函数时才返回。

如果没有参数传入 intersection() 函数,则返回原集合的副本。

Python set 交集函数案例

我们将声明两组集合,如上图1所示:

  • A: Python,JavaScript , PHP
  • B: Java,Python ,Ruby
    两个集合中都只有 Python,因此计算一个交集应该返回一个新的集合,这个集合的唯一元素是 Python。
A = {'Python', 'JavaScript', 'PHP'}
B = {'Java', 'Python', 'Ruby'}

print(f"A ∩ B = {A.intersection(B)}")

输出:

A ∩ B = {'Python'}

如果你没有为 intersection() 函数指定任何参数,那么返回一个集合的副本:

A = {'Python', 'JavaScript', 'PHP'}
print(f"A ∩ / = {A.intersection()}")

输出:

A ∩ / = {'JavaScript', 'PHP', 'Python'}

你可以通过打印内存地址来验证它是否被复制了:

A = {'Python', 'JavaScript', 'PHP'}
A_copy = A.intersection()
print(hex(id(A)))
print(hex(id(A_copy)))

输出:

0x108c68e40
0x108da5ac0

You won’t see the identical values, and that’s not the point. The important thing is that they’re different, indicating the set was copied to a different memory address.

One commonly asked question is how to find intersection of two lists, so let’s answer it now.

你不会看到相同的值,这不是重点。重要的是它们是不同的,这表明集合被复制到了不同的内存地址。

一个常见的问题是如何找到两个列表的交集,让我们现在回答它。

如何在 Python 中找到两个列表的交集

List is the most popular data type in Python – it’s used even in cases where a better data structure exists. There are numerous ways you find the intersection of two lists. We’ll cover two:

list(列表) 是 Python 中最流行的数据类型,甚至在存在更好的数据结构的情况下也会使用它。有许多方法可以找到两个列表的交集。我们将讨论两个:

  • list_intersection():通过使用列表理解。
  • list_intersection2() : 通过将单个列表转换为集合。
def list_intersection(l1: list, l2: list) -> list:
    return [val for val in l1 if val in l2]

def list_intersection2(l1: list, l2: list) -> list:
    return list(set(l1).intersection(l2))

A = ['Python', 'JavaScript', 'PHP']
B = ['Java', 'Python', 'Ruby']

print(f"A ∩ B v1 = {list_intersection(A, B)}")
print(f"A ∩ B v2 = {list_intersection2(A, B)}")

输出

A ∩ B v1 = ['Python']
A ∩ B v2 = ['Python']

使用 & 运算符计算交集

你不必每次都调用 intersection() 函数,你可以使用 & 操作符。

A = {'Python', 'JavaScript', 'PHP'}
B = {'Java', 'Python', 'Ruby'}

print(f"A ∩ B = {A & B}")

输出:

A ∩ B = {'Python'}

其他的都是一样的,记住两个操作数都必须设置为 & 运算符才能工作。

Python set Intersection 常见错误

在第一次使用集合时,可能会遇到错误。这些错误很常见,也很容易调试。

AttributeError: ‘list’ has no attribute intersection

这是最常见的错误,当错误的数据类型调用 intersection ()函数时,会出现,只有集合具有这种内置的功能。
下面是一个例子,当你使用列表时会引发一个异常:

A = ['Python', 'JavaScript', 'PHP']
B = ['Java', 'Python', 'Ruby']

print(f"A ∩ B = {A.intersection(B)}")

输出:

Image 4 – Attribute error on the set intersection (image by author)

确保两者都是集合类型,就可以正常运行。

TypeError: unsupported operand type(s) for &: ‘set’ and 'list’

在尝试对无效数据类型使用简写符号(& 符号)时发生此错误。两个操作数的类型必须为set 集合,简写符号才能工作。下面是一个例子:

A = {'Python', 'JavaScript', 'PHP'}
B = ['Java', 'Python', 'Ruby']
print(f"A ∩ B = {A & B}")

输出:

Image 5 – Type error on the set intersection (image by author)

如你所见,a 是一个集合,b 是一个列表,所以 & 符号不起作用。

Python set 交集问题

现在,我们将回顾一些关于 Python set intersection 函数的常见问题(FAQ)。

set intersection() 和 Intersection_update() 的区别
The intersection_update() function removes items that are not found in both sets (or multiple sets). The function is different from the intersection() function, as it removes unwanted elements from the original set and doesn’t return anything:

intersection_update() 函数的作用是:删除两个集合(或多个集合)中未找到的项。该函数与 intersection() 函数不同,因为它从原始集合中删除了不需要的元素,并且不返回任何内容。
输出:

{'Python'}

Python set 交集的相反操作是什么?

与 Python 集合交集相反的是对称差,即所有的元素只出现在第一个或第二个集合中,而不是两个集合中。

A = {'Python', 'JavaScript', 'PHP'}
B = {'Java', 'Python', 'Ruby'}

print(A.symmetric_difference(B))

输出:

{'Ruby', 'Java', 'PHP', 'JavaScript'}

你可以使用 ^ 操作符计算对称差:

A = {'Python', 'JavaScript', 'PHP'}
B = {'Java', 'Python', 'Ruby'}
print(A ^ B)

输出:

{'Ruby', 'Java', 'PHP', 'JavaScript'}

在 Python 中集合求交集的时间复杂度是多少?
The time complexity of set intersection in Python on a set with n elements and a set argument with m elements is O(min(n, m)) because you need to check for the smaller set whether each of its elements is a member of the larger set. Checking membership is O(1), according to finxter.com.

在 Python 中,在一个包含 n 个元素的集合和一个包含 m 个元素的集合参数上,集合相交的时间复杂度是 O(min(n, m)) ,因为需要检查较小的集合中的每个元素是否是较大集合中的一个成员。 finxter.com网站提供的时间复杂度是 O(1)

总结

Python 集合的交集非常容易理解。我们刚刚使用了可视化的例子进行辅助理解高级的用法,并展示了常见错误。我们也回答了一些常见的问题。

我希望本文能够帮助你更好地理解 Python set intersection 函数。像往常一样,如果你有任何问题或意见,请随时在下面的评论部分提问。Happy coding !

Learn More

本文翻译自 Python Set Intersection – The Ultimate Guide for Beginners,版权归属原作者所有。

Logo

学大模型,用大模型上飞桨星河社区!每天8点V100G算力免费领!免费领取ERNIE 4.0 100w Token >>>

更多推荐