对于三个参数,它看起来像:
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 :
>> >列表= [[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交叉(列表):返回列表(set.intersection(* map(set,lists)))如果您更喜欢 intersect()来接受任意数量的参数而不是单个参数,请使用它:
def intersect(* lists):返回列表(set.intersection(* map(set,lists)))
I define intersection of two lists as follows:
def intersect(a, b): return list(set(a) & set(b))For three arguments it would look like:
def intersect(a, b, c): return (list(set(a) & set(b) & set(c))Can I generalize this function for variable number of lists?
The call would look for example like:
>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]) [2]EDIT: Python can only achieve it this way?
intersect([ [1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2] ]) [2]解决方案
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)))
更多推荐
可变数量的列表的交集
发布评论