1、取交集

a = [1, 2, 3, 4, 5]
    b = [1, 2, 3, 7, 8]

    # 方法一:
    intersection = list(set(a).intersection(set(b)))
    print (intersection)
    # 方法二
    intersection = [i for i in a if i in b]
    print(intersection)

    # 结果输出 [1, 2, 3]

2、取并集

a = [1, 2, 3, 4, 5]
    b = [1, 2, 3, 7, 8]

    # 方法一:
    union = list(set(a).union(set(b)))
    print (union)

    # 结果输出 [1, 2, 3, 4, 5, 7, 8]

3、取差集

a = [1, 2, 3, 4, 5]
    b = [1, 2, 3, 7, 8]

    # 方法一:
    difference = list(set(b).difference(set(a)))  # b中有而a中没有的
    print (difference)

记录撸码一瞬间