python之set

打印 上一主题 下一主题

主题 1021|帖子 1021|积分 3063

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在 Python 中,set 是一种内置的数据类型,用于存储不重复的元素。set 是无序的,这意味着元素没有特定的次序。set 提供了一些有用的方法和操纵,可以用于集合运算,如并集、交集、差集等。
创建集合

你可以使用花括号 {} 或 set() 函数来创建集合。
  1. # 使用花括号创建集合
  2. fruits = {"apple", "banana", "cherry"}
  3. print(fruits)  # 输出: {'apple', 'banana', 'cherry'}
  4. # 使用 set() 函数创建集合
  5. numbers = set([1, 2, 3, 4, 5])
  6. print(numbers)  # 输出: {1, 2, 3, 4, 5}
复制代码
基本操纵

添加元素

使用 add() 方法可以向集合中添加元素。
  1. fruits = {"apple", "banana"}
  2. fruits.add("cherry")
  3. print(fruits)  # 输出: {'apple', 'banana', 'cherry'}
复制代码
移除元素

使用 remove() 或 discard() 方法可以从集合中移除元素。remove() 方法在元素不存在时会引发 KeyError 非常,而 discard() 方法不会。
  1. fruits = {"apple", "banana", "cherry"}
  2. fruits.remove("banana")
  3. print(fruits)  # 输出: {'apple', 'cherry'}
  4. # 使用 discard() 方法
  5. fruits.discard("banana")  # 不会引发异常
  6. print(fruits)  # 输出: {'apple', 'cherry'}
复制代码
清空集合

使用 clear() 方法可以清空集合。
  1. fruits = {"apple", "banana", "cherry"}
  2. fruits.clear()
  3. print(fruits)  # 输出: set()
复制代码
集合运算

并集

使用 union() 方法或 | 运算符可以计算两个集合的并集。
  1. set1 = {1, 2, 3}
  2. set2 = {3, 4, 5}
  3. union_set = set1.union(set2)
  4. print(union_set)  # 输出: {1, 2, 3, 4, 5}
  5. # 使用 | 运算符
  6. union_set = set1 | set2
  7. print(union_set)  # 输出: {1, 2, 3, 4, 5}
复制代码
交集

使用 intersection() 方法或 & 运算符可以计算两个集合的交集。
  1. set1 = {1, 2, 3}
  2. set2 = {3, 4, 5}
  3. intersection_set = set1.intersection(set2)
  4. print(intersection_set)  # 输出: {3}
  5. # 使用 & 运算符
  6. intersection_set = set1 & set2
  7. print(intersection_set)  # 输出: {3}
复制代码
差集

使用 difference() 方法或 - 运算符可以计算两个集合的差集。
  1. set1 = {1, 2, 3}
  2. set2 = {3, 4, 5}
  3. difference_set = set1.difference(set2)
  4. print(difference_set)  # 输出: {1, 2}
  5. # 使用 - 运算符
  6. difference_set = set1 - set2
  7. print(difference_set)  # 输出: {1, 2}
复制代码
对称差集

使用 symmetric_difference() 方法或 ^ 运算符可以计算两个集合的对称差集。
  1. set1 = {1, 2, 3}
  2. set2 = {3, 4, 5}
  3. symmetric_difference_set = set1.symmetric_difference(set2)
  4. print(symmetric_difference_set)  # 输出: {1, 2, 4, 5}
  5. # 使用 ^ 运算符
  6. symmetric_difference_set = set1 ^ set2
  7. print(symmetric_difference_set)  # 输出: {1, 2, 4, 5}
复制代码
其他方法

判断元素是否在集合中

使用 in 关键字可以判断元素是否在集合中。
  1. fruits = {"apple", "banana", "cherry"}
  2. print("apple" in fruits)  # 输出: True
  3. print("grape" in fruits)  # 输出: False
复制代码
集合长度

使用 len() 函数可以获取集合的长度。
  1. fruits = {"apple", "banana", "cherry"}
  2. print(len(fruits))  # 输出: 3
复制代码
总结



  • set 是一种无序且不重复的集合类型。
  • 可以使用 {} 或 set() 创建集合。
  • 提供了添加、移除、清空等基本操纵。
  • 支持并集、交集、差集

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

知者何南

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表