xra*_*alf 4 python intersection function list set
我定义了两个列表的交集,如下所示:
def intersect(a, b):
return list(set(a) & set(b))
Run Code Online (Sandbox Code Playgroud)
对于三个参数,它看起来像:
def intersect(a, b, c):
return (list(set(a) & set(b) & set(c))
Run Code Online (Sandbox Code Playgroud)
我可以针对可变数量的列表推广此函数吗?
电话会看起来像:
>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2])
[2]
Run Code Online (Sandbox Code Playgroud)
编辑:Python只能这样实现吗?
intersect([
[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]
])
[2]
Run Code Online (Sandbox Code Playgroud)
Thi*_*ter 15
使用*-list-to-argument运算符而不是自定义函数使用set.intersection:
>>> lists = [[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]]
>>> list(set.intersection(*map(set, lists)))
[2]
Run Code Online (Sandbox Code Playgroud)
如果你想在一个函数中使用list-to-set-to-list逻辑,你可以这样做:
def intersect(lists):
return list(set.intersection(*map(set, lists)))
Run Code Online (Sandbox Code Playgroud)
如果您更愿意intersect()接受任意数量的参数而不是单个参数,请改用:
def intersect(*lists):
return list(set.intersection(*map(set, lists)))
Run Code Online (Sandbox Code Playgroud)