common element in some lists - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: News and Discussions (https://python-forum.io/forum-31.html) +--- Thread: common element in some lists (/thread-33727.html) |
common element in some lists - Skaperen - May-21-2021 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. RE: common element in some lists - Gribouillis - May-21-2021 Try set.intersection(*others)
RE: common element in some lists - Skaperen - May-21-2021 and if what i get are not sets? RE: common element in some lists - Gribouillis - May-21-2021 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'} RE: common element in some lists - Skaperen - May-23-2021 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' >>> |