Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find (and keep) duplicates of sublist in python

I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.

Example:

x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]

output => [3, 4]

How can I do this?

like image 221
Mike Avatar asked Nov 12 '09 15:11

Mike


2 Answers

common = set(x[0])
for l in x[1:]:
    common &= set(l)
print list(common)

or:

import operator
print reduce(operator.iand, map(set, x))
like image 118
Ned Batchelder Avatar answered Nov 15 '22 05:11

Ned Batchelder


In one liner:

>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
like image 36
Nadia Alramli Avatar answered Nov 15 '22 05:11

Nadia Alramli