马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在 Python 中,set 是一种内置的数据类型,用于存储不重复的元素。set 是无序的,这意味着元素没有特定的次序。set 提供了一些有用的方法和操纵,可以用于集合运算,如并集、交集、差集等。
创建集合
你可以使用花括号 {} 或 set() 函数来创建集合。
- # 使用花括号创建集合
- fruits = {"apple", "banana", "cherry"}
- print(fruits) # 输出: {'apple', 'banana', 'cherry'}
- # 使用 set() 函数创建集合
- numbers = set([1, 2, 3, 4, 5])
- print(numbers) # 输出: {1, 2, 3, 4, 5}
复制代码 基本操纵
添加元素
使用 add() 方法可以向集合中添加元素。
- fruits = {"apple", "banana"}
- fruits.add("cherry")
- print(fruits) # 输出: {'apple', 'banana', 'cherry'}
复制代码 移除元素
使用 remove() 或 discard() 方法可以从集合中移除元素。remove() 方法在元素不存在时会引发 KeyError 非常,而 discard() 方法不会。
- fruits = {"apple", "banana", "cherry"}
- fruits.remove("banana")
- print(fruits) # 输出: {'apple', 'cherry'}
- # 使用 discard() 方法
- fruits.discard("banana") # 不会引发异常
- print(fruits) # 输出: {'apple', 'cherry'}
复制代码 清空集合
使用 clear() 方法可以清空集合。
- fruits = {"apple", "banana", "cherry"}
- fruits.clear()
- print(fruits) # 输出: set()
复制代码 集合运算
并集
使用 union() 方法或 | 运算符可以计算两个集合的并集。
- set1 = {1, 2, 3}
- set2 = {3, 4, 5}
- union_set = set1.union(set2)
- print(union_set) # 输出: {1, 2, 3, 4, 5}
- # 使用 | 运算符
- union_set = set1 | set2
- print(union_set) # 输出: {1, 2, 3, 4, 5}
复制代码 交集
使用 intersection() 方法或 & 运算符可以计算两个集合的交集。
- set1 = {1, 2, 3}
- set2 = {3, 4, 5}
- intersection_set = set1.intersection(set2)
- print(intersection_set) # 输出: {3}
- # 使用 & 运算符
- intersection_set = set1 & set2
- print(intersection_set) # 输出: {3}
复制代码 差集
使用 difference() 方法或 - 运算符可以计算两个集合的差集。
- set1 = {1, 2, 3}
- set2 = {3, 4, 5}
- difference_set = set1.difference(set2)
- print(difference_set) # 输出: {1, 2}
- # 使用 - 运算符
- difference_set = set1 - set2
- print(difference_set) # 输出: {1, 2}
复制代码 对称差集
使用 symmetric_difference() 方法或 ^ 运算符可以计算两个集合的对称差集。
- set1 = {1, 2, 3}
- set2 = {3, 4, 5}
- symmetric_difference_set = set1.symmetric_difference(set2)
- print(symmetric_difference_set) # 输出: {1, 2, 4, 5}
- # 使用 ^ 运算符
- symmetric_difference_set = set1 ^ set2
- print(symmetric_difference_set) # 输出: {1, 2, 4, 5}
复制代码 其他方法
判断元素是否在集合中
使用 in 关键字可以判断元素是否在集合中。
- fruits = {"apple", "banana", "cherry"}
- print("apple" in fruits) # 输出: True
- print("grape" in fruits) # 输出: False
复制代码 集合长度
使用 len() 函数可以获取集合的长度。
- fruits = {"apple", "banana", "cherry"}
- print(len(fruits)) # 输出: 3
复制代码 总结
- set 是一种无序且不重复的集合类型。
- 可以使用 {} 或 set() 创建集合。
- 提供了添加、移除、清空等基本操纵。
- 支持并集、交集、差集
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |