1 list的集合运算
1.1 交集
方法1:朴素的遍历;如果列表出现重复元素,该方法会出现问题,重复元素可能会保留。
1 2 3 4 5 6 7 8 9 10 11
| a = [2, 3, 4, 5] b = [2, 5, 8] tmp = [val for val in a if val in b] print(tmp)
a = [2, 2, 3, 4, 5] b = [2, 5, 8] tmp = [val for val in a if val in b] print(tmp)
|
方法2:转化为set操作,速度快;重复元素不会保留。
1 2 3 4 5 6 7 8 9
| a = [2, 3, 4, 5] b = [2, 5, 8] print(list(set(a).intersection(set(b))))
a = [2, 2, 3, 4, 5] b = [2, 5, 8] print(list(set(a).intersection(set(b))))
|
1.2 并集
方法1:
1 2 3
| a = [2, 3, 4, 5] b = [2, 5, 8] print(list(set(a+b)))
|
方法2:
1 2 3
| a = [2, 3, 4, 5] b = [2, 5, 8] print(list(set(a).union(set(b))))
|
1.3 差集
方法1:朴素的遍历;如果列表出现重复元素,该方法会出现问题,重复元素可能会保留。
1 2 3 4 5 6 7 8 9 10 11
| a = [2, 3, 4, 5] b = [2, 5, 8] tmp = [val for val in b if val not in a] print(tmp)
a = [2, 3, 4, 5] b = [2, 5, 8, 8] tmp = [val for val in b if val not in a] print(tmp)
|
方法2:转化为set操作,速度快;重复元素不会保留。
1 2 3 4 5 6 7 8 9
| a = [2, 3, 4, 5] b = [2, 5, 8] print(list(set(b).difference(set(a))))
a = [2, 3, 4, 5] b = [2, 5, 8, 8] print(list(set(b).difference(set(a))))
|
2 set的集合运算
1 2 3 4 5 6 7 8 9 10 11
| s = set([3, 5, 9, 10, 20, 40]) t = set([3, 5, 9, 1, 7, 29, 81])
print(t | s)
print(t & s)
print(t - s)
print(t ^ s)
|