两个集合:
a = [1,2,3,4,5,6]
b = [3,5,7]
1.求交集
方式一:
intersection = [i for i in a if i in b]
intersection = list(set(a).intersection(set(b)))
结果: [3, 5]
2.求并集
union= list(set(a).union(set(b)))
结果: [1, 2, 3, 4, 5, 6, 7]
3. 求差集
在b中但不在a中
subtraction = list(set(b).difference(set(a)))
结果:[7]
在a中但不在b中
subtraction = list(set(a).difference(set(b)))
结果:[1, 2, 4, 6]
参考:https://blog.youkuaiyun.com/bitcarmanlee/article/details/51622263
本文介绍如何使用Python进行集合的基本操作,包括求交集、并集和差集等,并提供了具体的代码实现示例。

被折叠的 条评论
为什么被折叠?



