在上周的文章中,你已经了解了 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 。我们将在整篇文章中使用这两个集合,这样只是为了保持简单,当更多集合相交时,同样的逻辑也适用。

请看以下两组:

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。为什么?因为它是两个集合中唯一相同的元素。

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

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

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)}")

输出:

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

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

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

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

输出:

如你所见,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 Union
  • Python Set Difference
  • Python If-Else Statement in One Line – Ternary Operator Explained

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

Python Set 集合交集 intersection | 初学者的终极指南【翻译】相关推荐

  1. [转载] Python集合取交集intersection()函数和intersection_update()函数

    参考链接: Python中的intersection函数 Python集合取交集intersection()函数. 取交集.intersection()函数. 程序实例1: intersection( ...

  2. python 并集union, 交集intersection, 差集difference, 对称差集symmetric_difference

    python的集合set和其他语言类似,是一个无序不重复元素集, 可用于消除重复元素. 支持union(联合), intersection(交), difference(差)和sysmmetric d ...

  3. python 并集union, 交集intersection, 差集difference

    python的集合set和其他语言类似,是一个无序不重复元素集, 可用于消除重复元素. 支持union(联合), intersection(交), difference(差)和sysmmetric d ...

  4. python set集合 交集,并集,差集,对称差集

    set集合测试打印如下: setA={1,2,3,4} setB={3,4,5,6} print(setA-setB) >>> {1, 2} - 取差集 print(setB-set ...

  5. Python中求集合交集的intersection()方法

    选择题 以下python代码的输出结果是什么? set0 = {'a','b','c'} set1 = {'b','c','d'} set2 = {'c','d','e'} newset = set0 ...

  6. 站长在线Python精讲:Python中集合的交集、并集、差集和对称差集运算方法详解

    欢迎你来到站长在线的站长学堂学习Python知识,本文学习的是<Python中集合的交集.并集.差集和对称差集运算方法详解>.主要讲的是集合运算的相关的概念,及运算方法,包括:集合的交集. ...

  7. Python的集合set

    set是python中一个无序且无重复元素的数据结构.无序,是因为set采用了hash技术进行元素的存储:无重复元素,本身就是set区别其他数据结构的一个重要特点,也是set之间能够进行并,交,差等各 ...

  8. Python set集合 - Python零基础入门教程

    目录 一.set 集合简介 二.set 集合常用函数 三.set 集合运算符 四.猜你喜欢 零基础 Python 学习路线推荐 : Python 学习目录 >> Python 基础入门 在 ...

  9. python中集合运算_入门 | 一文带你了解Python集合与基本的集合运算

    原标题:入门 | 一文带你了解Python集合与基本的集合运算 选自DataCamp 作者:Michael Galarnyk 参与:Geek Ai.思源 一般我们熟悉 Python 中列表.元组及字典 ...

最新文章

  1. Manning、Ostendorf、Povey、何晓冬、周明共话多模态NLP的机遇和挑战(附视频)
  2. monty python flying circus-巨蟒剧团之飞翔的马戏团 第一季
  3. mysql delimiter 作用
  4. lightoj 1300 边双联通分量+交叉染色求奇圈
  5. centos7安装docker-ce新版
  6. jsp页面获取系统的日期时间
  7. C# list删除 另外list里面的元素_[Python]列表(list)操作
  8. 主席树 || 可持久化线段树 || BZOJ 3653: 谈笑风生 || Luogu P3899 [湖南集训]谈笑风生...
  9. Linux下安装qt5步骤
  10. Kettle_Spoon如何将MySQL数据抽取到ES
  11. Python3-word文档操作(七):提取word文档中的图片方式一-利用word文档的压缩文件属性
  12. 弗洛伊德的兔子与乌龟
  13. 艾艾贴redis集群
  14. 极客日报:库克对话何同学:苹果很多功能来自中国消费者反馈;高通、微软、谷歌联合施压监管方:反对NVIDIA收购ARM...
  15. MUR20060CT-ASEMI快恢复模块200A 600V
  16. 谈谈实体的 ID 与“键”
  17. 港澳联考数学可以用计算机吗,2017年港澳台联考数学试卷.doc
  18. Kafka安装与验证
  19. htlm5实习报告_网页 实习报告
  20. mimikatz的基本使用

热门文章

  1. 03 PF-Net: Point Fractal Network for 3D Point Cloud Completion
  2. 六款主流ETL工具介绍及功能对比
  3. 用Excel制作不一样的百分比信息图表(3)
  4. 【vim】撤销和恢复撤销快捷键
  5. 论文参考文献格式大全
  6. 文章植入广告营销系统开发
  7. 如何在电脑录屏?win10录屏快捷键ctrl+alt+
  8. 登陆凯叔讲故事显示未链接服务器,凯叔用户暴涨的秘密
  9. Aqua-Fi发明水下WiFi,从此星辰大海
  10. android 6.0在关机界面添加截图功能