python交集和补集的符号_python数组并集交集补集

这篇博客介绍了Python中集合的基本操作,包括如何合并两个数组得到并集,如何找到两个数组的交集,以及如何获取一个集合相对于另一个集合的补集。示例代码展示了使用extend()、set()、&、|和-等操作符实现这些功能。
摘要由CSDN通过智能技术生成

并集a = ["a", "b", "c", "d"]

b = ["b", "e"]

c = ["a", "b", "c", "d", "e"]

# 并

# 合并数组

a.extend(b)

# 去重

array = list(set(a))

print(array)

# 第二种方法

array = list(set(a)|set(b))

print(array)

打印结果:['c', 'a', 'b', 'd', 'e']

['c', 'a', 'b', 'd', 'e']

交集a = ["a", "b", "c", "d"]

b = ["b", "e"]

c = ["a", "b", "c", "d", "e"]

# 交

array = list(set(a) & set(b))

print(array)

打印结果:['b', 'e']

补集a = ["a", "b", "c", "d"]

b = ["b", "e"]

c = ["a", "b", "c", "d", "e"]

# 补

print(set(c))

print(set(a))

array = list(set(c)-set(a))

print(array)

打印结果:['e']

Python中,可以使用集合(set)来进行交集并集、差集和补集的操作。 1. 交集:两个集合中共同存在的元素构成的新集合。可以使用`&`算符或者`intersection()`方法来实现。 示例代码: ``` set1 = {1, 2, 3} set2 = {2, 3, 4} intersection_set = set1 & set2 # 或者使用 intersection() 方法 # intersection_set = set1.intersection(set2) print(intersection_set) # 输出: {2, 3} ``` 2. 并集:两个集合中所有的元素构成的新集合。可以使用`|`运算符或者`union()`方法来实现。 示例代码: ```python set1 = {1, 2, 3} set2 = {2, 3, 4} union_set = set1 | set2 # 或者使用 union() 方法 # union_set = set1.union(set2) print(union_set) # 输出: {1, 2, 3, 4} ``` 3. 差集:第一个集合中存在,而第二个集合中不存在的元素构成的新集合。可以使用`-`运算符或者`difference()`方法来实现。 示例代码: ```python set1 = {1, 2, 3} set2 = {2, 3, 4} difference_set = set1 - set2 # 或者使用 difference() 方法 # difference_set = set1.difference(set2) print(difference_set) # 输出: {1} ``` 4. 补集:在全集中存在,但是不在指定集合中的元素构成的新集合。可以使用`^`运算符或者`symmetric_difference()`方法来实现。 示例代码: ```python set1 = {1, 2, 3} set2 = {2, 3, 4} complement_set = set1 ^ set2 # 或者使用 symmetric_difference() 方法 # complement_set = set1.symmetric_difference(set2) print(complement_set) # 输出: {1, 4} ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值