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!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

>>> p=[ [1,2,3],
    [1,9,9],
    [1,2,4]]
>>> set(p[0]).intersection(*p)
set([1])

Method 3

A simple solution (one-line) is:

set.intersection(*[set(list) for list in p])

Method 4

Why not just:

set.intersection(*map(set, p))

Result:

set([1])

Or like this:

ip = iter(p)
s = set(next(ip))
s.intersection(*ip)

Result:

set([1])

edit:

copied from console:

>>> p = [[1,2,3], [1,9,9], [1,2,4]]
>>> set.intersection(*map(set, p))
set([1])
>>> ip = iter(p)
>>> s = set(next(ip))
>>> s.intersection(*ip)
set([1])

Method 5

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

ans = [ele[0] for ele in zip(*p) if len(set(ele)) == 1]

Result:

>>> ans
[1]

Method 6

reduce(lambda x, y: x & y, (set(i) for i in p))

Method 7

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

However, there is a limitation of 10 lists in a list. Anything bigger causes ‘result’ list to be out of order. Assuming you’ve made ‘result’ into a list by list(result).

Make sure you result.sort() to ensure it’s ordered if you depend on it to be that way.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x