可变数量列表的交集

时间:2012-06-02 09:34:39

标签: python list function set intersection

我定义两个列表的交集如下:

def intersect(a, b):
  return list(set(a) & set(b))

对于三个参数,它看起来像:

def intersect(a, b, c):
  return (list(set(a) & set(b) & set(c))

我可以针对可变数量的列表推广此函数吗?

电话会看起来像:

>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2])
[2]
编辑:Python只能通过这种方式实现吗?

intersect([
          [1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]
         ])
[2]

2 个答案:

答案 0 :(得分:15)

使用*-list-to-argument operator而不是自定义函数使用set.intersection

>>> lists = [[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]]
>>> list(set.intersection(*map(set, lists)))
[2]

如果你想在一个函数中使用list-to-set-to-list逻辑,你可以这样做:

def intersect(lists):
    return list(set.intersection(*map(set, lists)))

如果您希望intersect()接受任意数量的参数而不是单个参数,请改用:

def intersect(*lists):
    return list(set.intersection(*map(set, lists)))

答案 1 :(得分:0)

def intersect(*lists):
    if(len(lists) <=1):
        return lists[0]

    result = lists[0]
    for i in range(1, len(lists)):
        result = set(result) & set(lists[i])

    return list(result)

就像这样调用函数......

intersect([1,2],[2,3],[2,4])

给你所有的卫生设施。

相关问题