我定义两个列表的交集如下:
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]
最佳答案
使用 *
-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]
如果你想在一个函数中实现列表到设置到列表的逻辑,你可以这样做:
def intersect(lists):
return list(set.intersection(*map(set, lists)))
如果您更喜欢 intersect()
接受任意数量的参数而不是单个参数,请改用它:
def intersect(*lists):
return list(set.intersection(*map(set, lists)))
关于python - 可变数量列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10861236/