Intersection of variable number of lists

假如想象 提交于 2019-12-05 12:36:37

Use the *-list-to-argument operator and instead of your custom function use set.intersection:

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

If you want the list-to-set-to-list logic inside a function, you can do it like this:

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

If you prefer intersect() to accept an arbitrary number of arguments instead of a single one, use this instead:

def intersect(*lists):
    return list(set.intersection(*map(set, lists)))
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)

Call the function just like this...

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

Leaving all sanitation to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!