交集、并集、差集最初是集合的基础运算,因此借助集合进行求解。
#已知list1和list2:每个list的元素是唯一的
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [2, 4, 6, 8, 10]
交集
#使用函数intersection
jj = list(set(list1).intersection(set(list2)))
并集
#使用函数union
bj = list(set(list1).union(set(list2)))
差集
#使用函数difference
cj = list(set(list1).difference(set(list2)))
# 值得注意的是,这里求的是list1-list2的差集,取决于顺序