python取交集、并集、差集

通过python取交集

    intersection = [i for i in a if i in b]
    intersection = list(set(a).intersection(set(b)))

取并集

print (list(set(a).union(set(b))))

取差集

print (list(set(b).difference(set(a)))) # b中有而a中没有的

对于多个数组求交集:

def fm(x, y):
    return list(set(x).intersection(set(y))) if isinstance(x, list) and isinstance(y, list) else 'error'


def fn(x):
    return x[0] if len(x) == 1 else [] if len(x) == 0 else reduce(fm, tuple(y for y in x))

 

你可能感兴趣的:(Python)