【python】并集交集
set是用来去重的。
在list里使用union函数。这种方式不适用于元素为字典的。
list(set(a)^set(b)) 这是求差集
所以交集就是并集和ab的差集。
import random def getRand(n): return [random.randint(0,100) for i in range(int(n))] a = getRand(10) b = getRand(10) print(a) print(b) c = list(set(a).union(set(b))) print("ab的并集是:") print(c) print("ab的交集是:") d = list( (set(a).union(set(b))) ^ set(a) ^ set(b)) print(d)
列表生成式
emmm...记得函数和函数之间空两行,被教育了
import random def getRand(n): return [random.randint(0,100) for i in range(int(n))] def union(a,b): return [x for x in set(a+b)] def inter(a,b): return [x for x in set(a) if x in set(b)] def main(): a = getRand(10) b = getRand(10) a = list(set(a)) b = list(set(b)) c = union(a,b) d = inter(a,b) print(a) print(b) print("并集是:") print(c) print("交集是:") print(d) main()