当前位置: 首页 > 后端技术 > Python

几种Python大集合的交集和并集运算方法和例子

时间:2023-03-26 00:31:15 Python

set这种数据类型和我们在数学中学习的集合非常相似。数学中的累加和求和运算也有交、并、差运算,python中的集合也是如此。一、求交集操作1、使用intersection()求交集:求交集时,可变集合和不可变集合的交集,使用哪个集合调用交集方法,返回结果是什么类型的集合。set7={'name',18,'python2','abc'}set8=frozenset({'name',19,'python3','abc'})res=set7.intersection(set8)#{'abc','name'}print(res,type(res))res=set8.intersection(set7)#frozenset({'abc','name'})print(res,type(res))返回结果:{'abc','name'}frozenset({'abc','name'})2.使用位运算符&运算符求交集set5={'name',18,'python2','abc'}set6={'name',19,'python3','abc'}set7={'name',18,'python2','abc''}set8=frozenset({'name',19,'python3','abc'})res=set5&set6print(res,type(res))res=set7&set8print(res,type(res))res=set8&set7#无论谁先到,返回的结果都是相同类型的setprint(res,type(res))Returnedresult:{'abc','name'}{'abc','name'}frozenset({'abc','name'})3.intersection_update()方法使用该方法计算交集然后将结果赋值给原始集合,是一个变化,所以它不适用于不可变集合set7={'name',18,'python2','abc'}set8=frozenset({'name',19,'python3','abc'})res=set7.intersection_update(set8)#无返回值print(set7,type(set7))#无返回值,直接打印赋值集合res=set8.intersection_update(set7)#不可变的sethasnointersection_updatemethodprint(res,type(res))returnstheresult:{'abc','name'}AttributeError:'frozenset'objecthasnoattribute'intersection_update'4.使用交集()方法当使用该方法求集合与其他数据类型的交集时,intersection()会直接将其他数据类型转为集合str1='python'list1=[1,2,3,18]tup1=(1,2,3,18)dict1={'name':'Tom','age':18,'love':'python'}set10={'name',18,'python','abc','p'}print(set10.intersection(str1))#返回:{'p'}而不是{'python'},因为str1转换成集合:{'y','t','p','o','n','h'}print(set10.intersection(list1))print(set10.intersection(tup1))print(set10.intersection(dict1))returnresult:{'p'}{18}{18}{'name'}2.并集运算1.使用union()求并集set5={'name',18,'python2','abc'}set6={'name',19,'python3','abc'}res=set5.union(set6)print(res,type(res))返回结果:{'python2','abc',18,19,'python3','name'}2。使用逻辑或|找到并集set5={'name',18,'python2','abc'}set6={'name',19,'python3','abc'}res=set5|set6print(res,type(res))返回结果:{'abc','python2','name','python3',18,19}3。使用update()求并集,只作用域变量set5={'name',18,'python2','abc'}set6={'name',19,'python3','abc'}res=set5.update(set6)#黄色波浪线表示该函数没有返回值print(set5,type(set5))returnstheresult:{'python2','pythonon3',18,'abc',19,'name'}上面讲了Python集合的交集和并集操作,并举例说明。当你第一次学习它时,它可能并不特别。明白了,做一次没关系,可以多做几次,还是看Python自学网的视频教程比较好。文字教程不一定能概括所有的知识点。来源:www.wakey.com.cn/document-set-flex.html