Return matches from an unknown number of python lists

I have a list containing 1-5 lists in it. I want to return only the values ​​that appear in all lists. I can easily throw an exception because there is only one list, but I cannot think about it when there are several (unknown number) lists. For instance:

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

will only return 2, because this is the only list item that will be displayed in all sub-lists

How can i achieve this?

+3
source share
3 answers
reduce(set.intersection, (set(x) for x in [[1,2,3,4],[2,3,7,8],[2,3,6,9],[1,2,5,7]]))
+4
source

You can use frozenset.intersection(or set.intersectionif you want):

>>> 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 the list if you want the result to be a list instead of a set.

+1

:

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))

, .

0

Source: https://habr.com/ru/post/1762624/


All Articles