Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find common elements in list of lists?

I'm trying to figure out how to compare an n number of lists to find the common elements. For example:

p=[ [1,2,3],
    [1,9,9],
      ..
      ..
    [1,2,4]

>> print common(p)
>> [1]

Now if I know the number of elements I can do comparions like:

for a in b:
  for c in d:
    for x in y:
...

but that wont work if I don't know how many elements p has. I've looked at this solution that compares two lists https://stackoverflow.com/a/1388864/1320800

but after spending 4 hrs trying to figure a way to make that recursive, a solution still eludes me so any help would be highly appreciated!

like image 320
8bits Avatar asked Apr 08 '12 21:04

8bits


People also ask

How do you find common elements in a list?

Method 1:Using Set's & property Convert the lists to sets and then print set1&set2. set1&set2 returns the common elements set, where set1 is the list1 and set2 is the list2. Below is the Python3 implementation of the above approach: Python3.

How do you find common elements in multiple lists?

You can transform the lists to sets, and then use Set. retainAll method for intersection between the different sets. Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.

How do you find the common element in three lists?

Algorithm. Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.

How do you find the common elements between three lists in Python?

Each list is iterated once to create the sets, and then the sets are intersected. The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a , so for longer list, this will be a lot less efficient.


3 Answers

You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set:

result = set(p[0])
for s in p[1:]:
    result.intersection_update(s)
print result
like image 158
Sven Marnach Avatar answered Oct 14 '22 21:10

Sven Marnach


The set.intersection() method supports intersecting multiple inputs at a time. Use argument unpacking to pull the sublists out of the outer list and pass them into set.intersection() as separate arguments:

>>> p=[ [1,2,3],
        [1,9,9],
        [1,2,4]]

>>> set(p[0]).intersection(*p)
set([1])
like image 28
Raymond Hettinger Avatar answered Oct 14 '22 21:10

Raymond Hettinger


A simple solution (one-line) is:

set.intersection(*[set(list) for list in p])
like image 39
WindChimes Avatar answered Oct 14 '22 20:10

WindChimes