0

consider a list of lists as given here.

many_lists = [[1,999,91,120,11], [909,800,7620,11], [1,101,800,7620]]

the output of this should be:

output_lst = [11, 1, 800, 7620]

I need to compare each list with the rest of the lists and if there is a common element then it should be in the output.

is there a simpler way to do this without two loops?

edit: (order within the output_list is not important)

  • Convert the lists to sets, intersect them, and convert the final result back to a list. – Barmar Jun 23 '21 at 06:04
  • Does this answer your question? [How to find common elements in list of lists?](https://stackoverflow.com/questions/10066642/how-to-find-common-elements-in-list-of-lists) –  Jun 23 '21 at 06:06
  • 1
    @Barmar I don't think that answers this because the intersection of all lists is empty here and is not the expected output. – Mustafa Aydın Jun 23 '21 at 06:07
  • I see, it's the elements that are common to any pair of sublists, not all sublists. – Barmar Jun 23 '21 at 06:09
  • @Barmar This is not a duplicate, OP wants to find items that appear in two lists at least, not all of them - and apparently in the order when the duplicates appear, but that should be made clear – Thierry Lathuille Jun 23 '21 at 06:09

2 Answers2

2

One way is to run a counter over the flattened list and choose those that appeared more than once:

from collections import Counter
from itertools import chain

flattened = chain.from_iterable(many_lists)

result = [elem
          for elem, count in Counter(flattened).items()
          if count > 1]

to get

>>> result
[1, 11, 800, 7620]
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
0

Without third loop, using set and intersaction:

many_lists = [[1,999,91,120,11], [909,800,7620,11], [1,101,800,7620]]

alist = []
for _ind, id in enumerate(many_lists):
    for j in many_lists[_ind+1:]:
        alist.append(list(set(id) & set(j)))
print(*alist)
Chandella07
  • 2,089
  • 14
  • 22