I have a list containing several lists of integers and I would like to find the lists having the maximum of common elements.
I tried to use the intersection, but it returns an empty set, since here the intersection concerns the common elements of all the lists found in my list. I would like my code to show me the lists having the common integer number that I want. If I want, for example, the lists having 3 integers in common, that it displays the lists in question to me. I have searched a lot on the net but I can only find reasoning to determine if two lists are identical or not.
Here is the code for intersection:
import string
list = [[3,5,9], [4,6,6], [4,7], [2,7], [2,1,4,5], [1,2,4,6], [3,3], [3,3], [3,2,1], [3,2]]
result = set.intersection(*map(set,list))
print(result)
Here is the result:
set()
but what I want is:
[2,1,4,5],[1,2,4,6]
CodePudding user response:
What you want is filtering the pairs of lists based on the condition of having 3 items in the intersection.
You can get all the pairs by using itertools.combinations
and filter them with a list comprehension:
import string
from itertools import combinations
list_ = [[3,5,9], [4,6,6], [4,7], [2,7], [2,1,4,5], [1,2,4,6], [3,3], [3,3], [3,2,1], [3,2]]
print([c for c in combinations(list_, r=2) if len(set(c[0]) & set(c[1])) == 3])
The output is as requested:
[([2, 1, 4, 5], [1, 2, 4, 6])]
CodePudding user response:
I'm a little confused by your wording but I think this is what you're looking for:
data = [[3, 5, 9], [4, 6, 6], [4, 7], [2, 7], [2, 1, 4, 5], [1, 2, 4, 6], [3, 3], [3, 3], [3, 2, 1], [3, 2]]
max_unique_elements = 0
holding = []
for data_list in data:
unique_elements = len(set(data_list))
if unique_elements > max_unique_elements:
holding = [data_list]
max_unique_elements = unique_elements
elif unique_elements == max_unique_elements:
holding.append(data_list)
print(holding)