开发手册 欢迎您!
软件开发者资料库

Python 集合(set) intersection_update() 方法

Python的集合(set)和其他语言类似, 是一个无序不重复元素集, 基本功能包括关系测试和消除重复元素. 集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric difference(对称差集)等数学运算。本文主要介绍Python 集合(set) intersection_update() 方法。

Python 集合方法

例如:

删除xy都不存在的元素:

x = {"apple", "banana", "cherry"}y = {"google", "microsoft", "apple"}x.intersection_update(y)print(x)

1、定义和用法

intersection_update()方法删除两个集合中不存在的元素(如果在两个以上集合之间进行比较,则删除所有集合中不存在的元素),即计算交集。

intersection_update()方法与intersection()方法不同,因为intersection()方法返回一个新的集合,不包含不需要的元素,而intersection_update()方法则从原始集合中删除不需要的元素。

2、调用语法

set.intersection_update(set1, set2 ... etc)

3、参数说明

参数

描述

set1

必需的参数,要查找相同元素的集合

set2

可选的。其他要查找相同元素的集合,可以多个,多个使用逗号 , 隔开

4、使用示例

例如:

比较3个集合,返回一个集合,其中包含所有3个集合中存在的项:

x = {"a", "b", "c"}y = {"c", "d", "e"}z = {"f", "g", "c"}x.intersection_update(y, z)print(x)

Python 集合方法