Python 获取多个list数组的交集的方法

本文主要介绍Python中,获取多个list数组的交集的方法几种方法,以及相关的示例代码。

示例代码:

[[1,3,5,7], [1,1,3,5,7], [1,4,7,9]] 

输出:

[1,7]

1、使用itertools实现

from itertools import cycle
def intersection(data):
    ITERATOR, VALUE = 0, 1
    n = len(data)
    result = []
    try:
        pairs = cycle([(it := iter(sublist)), next(it)] for sublist in data)
        pair = next(pairs)
        curr = pair[VALUE]  # Candidate is the largest value seen so far
        matches = 1         # Number of pairs where the candidate occurs
        while True:
            iterator, value = pair = next(pairs)
            while value < curr:
                value = next(iterator)
            pair[VALUE] = value
            if value > curr:
                curr, matches = value, 1
                continue
            matches += 1
            if matches != n:
                continue
            result.append(curr)
            while (value := next(iterator)) == curr:
                pass
            pair[VALUE] = value
            curr, matches = value, 1
    except StopIteration:
        return result

或者

def intersection(data):
    ITERATOR, VALUE = 0, 1
    n = len(data)
    result = []
    try:
        pairs = cycle([(it := iter(sublist)), next(it)] for sublist in data)
        pair = next(pairs)
        curr = pair[VALUE]  # Candidate is the largest value seen so far
        matches = 1         # Number of pairs where the candidate occurs
        while True:
            iterator, value = pair = next(pairs)
            while value < curr:
                value = next(iterator)
            pair[VALUE] = value
            if value > curr:
                curr, matches = value, 1
                continue
            matches += 1
            if matches != n:
                continue
            result.append(curr)
            for i in range(n):
                iterator, value = pair = next(pairs)
                pair[VALUE] = next(iterator)
            curr, matches = pair[VALUE], 1
    except StopIteration:
        return result

调用:

data = [[1,3,5,7],[1,1,3,5,7],[1,4,7,9]]
print(intersection(data))
[1, 7]

2、使用reduce实现

from functools import reduce
a = [[1,3,5,7],[1,1,3,5,7],[1,4,7,9]] 
print(reduce(lambda x, y: x & set(y), a[1:], set(a[0])))

3、使用set实现

d = [[1,3,5,7],[1,1,3,5,7],[1,4,7,9]] 
result = set(d[0]).intersection(*d[1:])
print(result)

推荐阅读
cjavapy编程之路首页