python数组(list) 求交集、并集、差集

两个集合:
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.csdn.net/bitcarmanlee/article/details/51622263

你可能感兴趣的:(Python)