Python求数组的并集、交集、差集

设有两个集合

A=[1,5,8,3,2]

B=[1,2,3]

1、求并集

union=list(set(A).union(set(B)))
print(union)

 

2、求交集

intersection=list(set(A).intersection(set(B)))\
print(intersection)

 

3、求差集

difference=list(set(A).difference(set(B)))
print(difference)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值