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)

5
  • Convert the lists to sets, intersect them, and convert the final result back to a list. Commented Jun 23, 2021 at 6:04
  • Does this answer your question? How to find common elements in list of lists? Commented Jun 23, 2021 at 6: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. Commented Jun 23, 2021 at 6:07
  • I see, it's the elements that are common to any pair of sublists, not all sublists. Commented Jun 23, 2021 at 6: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 Commented Jun 23, 2021 at 6:09

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

you can also flatten with sum(many_lists, [])
@oskros true, but that's an anti-pattern perhaps :)
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.