Intersection of variable number of lists

I define the intersection of two lists as follows:

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

For three arguments, it will look like this:

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

Can I generalize this function to a variable number of lists?

The call will look like this:

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

EDIT: Can Python achieve this only this way?

 intersect([ [1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2] ]) [2] 
+4
source share
2 answers

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

 >>> 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-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 one, use instead:

 def intersect(*lists): return list(set.intersection(*map(set, lists))) 
+15
source
 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 a function just like this ...

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

Leaving all the sanitation to you.

0
source

Source: https://habr.com/ru/post/1415702/


All Articles