tags:

views:

39

answers:

3

I have a list which contains 1-5 lists within it. I want to return only the values which appear in all the lists. I can easily create an exception for it there is only one list, but I can't think of a way round it when there are an multiple (unknown number of) lists. For example:

[[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]

would only return 2, because it's the only list item to appear in all the sub-lists

How can I achieve this?

+4  A: 
reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]))
Ignacio Vazquez-Abrams
Thanks, that does exactly what I needed
chrism
+1  A: 

You can use frozenset.intersection (or set.intersection if you prefer):

>>> l = [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]
>>> frozenset.intersection(*(frozenset(x) for x in l))
frozenset({2})

Add a call to list if you want the result as a list instead of a set.

Mark Byers
A: 

I suggest this solution:

s = [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]

#flatten the list
flat = sum(s,[])

#only keep digits that appear a certain number of times (size of s)
filtered = filter(lambda x: flat.count(x) == len(s),flat)

# clear repeated values
list(set(filtered))

There are better ways to do this but this one is more explicit.

pma
That... doesn't look any sort of explicit to me.
Ignacio Vazquez-Abrams
It is more explicit as it shows all the stages of filtering what chrism needs. I think the other answers do the job but are not so easy to understand.
pma