Python Forum
common element in some lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
common element in some lists
#1
i am wanting a function that does this. i get a list of list (any type sequence of any type sequences). it can even be sets (of course the inner containers must be hashable when the outer container is a set). what i want to find are all things that are in all the inner containers. i could create such a function. but i would like to know if python already has such a thing. if not, is there one in pypy (since the usage of this is for myself). i cannot imagine a name for this to be able to search for it.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Try set.intersection(*others)
Reply
#3
and if what i get are not sets?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Convert to set
>>> L = ["caoutchouc", "metro-boulot-dodo", "yaourth", "automobile"]
>>> set.intersection(*(set(x) for x in L))
{'u', 't', 'o'}
Actually, you can convert only the first one to set
>>> set(L[0]).intersection(*L[1:])
{'u', 't', 'o'}
Reply
#5
Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> L=[[list,dict,set],[list,str,set],[dict,bool,set]]
>>> set.intersection(*(set(x) for x in L))
{<class 'set'>}
>>> L=[[[],list,dict,set],[list,str,set],[dict,bool,set]]
>>> set.intersection(*(set(x) for x in L))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
TypeError: unhashable type: 'list'
>>>
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020