求两个列表的交集、差集、并集---面试

求两个列表的交集、差集、并集。

 1 a = [1, 2, 3, 6]
 2 b = [8, 3, 5, 6]
 3 jj1 = [i for i in a if i in b]  # 在a中的i,并且也在b中,这就是交集
 4 jj2 = list(set(a).intersection(set(b)))  # 使用intersection方法求交集
 5 
 6 bj1 = list(set(a).union(set(b)))  # 使用union方法求并集
 7 
 8 cj1 = list(set(b).difference(set(a)))  # b中有而a中没有的
 9 cj2 = list(set(a).difference(set(b)))  # a中有而b中没有的
10 
11 print("交集:", jj1)
12 print("交集:", jj2)
13 
14 print("并集:", bj1)
15 
16 print("差集(b中有而a中没有的):", cj1)
17 print("差集(a中有而b中没有的):", cj2)

运行结果:

原文地址:https://www.cnblogs.com/annatest/p/13631201.html