Python3中update与union、intersection_update 与intersetion的区别

Python3中update与union、intersection_update 与intersetion的区别

  • Python3中的集合内建函数比较

Python3中的集合内建函数比较

在Python3中,集合的运算可以通过运算符来实现交集、并集、差集,示例如下:

aSet=set('boyfriend')
bSet=set('girlfriend')
aSet.union(bSet)
Out[69]: {'b', 'd', 'e', 'f', 'g', 'i', 'l', 'n', 'o', 'r', 'y'}
aSet
Out[70]: {'b', 'd', 'e', 'f', 'i', 'n', 'o', 'r', 'y'}
aSet.intersection(bSet)
Out[71]: {'d', 'e', 'f', 'i', 'n', 'r'}
aSet
Out[72]: {'b', 'd', 'e', 'f', 'i', 'n', 'o', 'r', 'y'}

在上述示例中,可以观察到集合aSet和集合bSet实现了交集和并集,但是生成的是一个新的集合,并没有在原有的集合上面修改(换言之,原集合不发生改变)

在Python3中还有一类函数也可以实现集合的交集和并集,即update()和intersection_update(),示例代码如下:

aSet=set('boyfriend')
bSet=set('girlfriend')
aSet.update(bSet)
aSet
Out[3]: {'b', 'd', 'e', 'f', 'g', 'i', 'l', 'n', 'o', 'r', 'y'}


aSet=set('boyfriend')
bSet=set('girlfriend')
aSet.intersection_update(bSet)
aSet
Out[10]: {'d', 'e', 'f', 'i', 'n', 'r'}

在上述例子中,观察到可以通过update()和intersection_update()实现并集和交集,不过原集合发生了变化(即,集合的交并是在原集合的基础上进行的,没有生成新的集合)

你可能感兴趣的:(Python3,Python3集合的内建函数)