python之set

在 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() 创建集合。
  • 提供了添加、移除、清空等基本操作。
  • 支持并集、交集、差集
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼爱吃火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值