Home > Software engineering >  Return common elements appear one or multiple times in a list of list
Return common elements appear one or multiple times in a list of list

Time:09-30

list_of_list=[[1,2,3,4,133,90],[4,11,22,99,3],[5,3,22,66,12,10],[1,99,101]]

the code should return elements that can be common with one or multiple sublists.

output: [1,3,4,22,99]

what I have tried from stack overflow:
a = [1, 2, 3, 4]
b = [2, 3, 4, 5, 6]
c = [3, 4, 5, 6, 10, 12]
elements_in_all = list(set.union(*map(set, [a, b, c])))
elements_in_all
why it's not solving my case:

doing mapping and set intersection which only picks common elements if the elements appeared in all sublists.
But in my case, the element can be common in one single sublist or in all sublists.


Can anyone suggest a pythonic way to solve this problem?

CodePudding user response:

c = collections.Counter()
for sub in list_of_list:
    c.update(set(sub))

this creates a mapping element => number of sublists, from which you can pick whatever you want, for example:

[v for v, cnt in c.items() if cnt > 1] 

to make a list of elements that occur in at least two lists.

CodePudding user response:

import itertools
import collections

list_of_lists = [[1,2,3,4,133,90],[4,11,22,99,3],[5,3,22,66,12,10],[1,99,101]]

# Get the combinations which have a repeating element
repeating = [element for element in itertools.product(*list_of_lists) 
             if len(set(element)) != len(list_of_lists)]


# Take only the elements which appear more than once
more_than_once = []

for element in repeating:
    more_than_once.append([item for item, count in 
                           collections.Counter(element).items() if count > 1])


# Get uniques
uniques = set()

for m in more_than_once:
    for item in m:
        uniques.add(item)

unique_list = list(uniques)

unique_list = [1, 3, 4, 22, 99]

CodePudding user response:

Here's a version closer in sprit to your posted code:

list(set.union(*[a.intersection(b) 
     for a, b in itertools.combinations(map(set, list_of_list), 2)]))
  • Related