Search code examples
pythonlistindexinglist-comprehensionnested-lists

How to get common elements in a deep nested list: my two solutions work but take some time


I have a nested list structure as below. Each of the 4 nested structures represents some free positions for me. I want to find which elements are present in all 4 nested lists.

ary=[   [[0, 4], [5, 11]],    [[0, 2], [0, 4], [5,10]],  [[0, 4], [0, 14], [5,11]],  [[0, 4], [0, 14], [5,11]]  ]

As in above, in the first nested list [[0, 4], [5, 11]], the [0,4] is present in all but [5,11] is not. Hence, my answer should be [[0,4]] or even just [0,4].

I did this in two ways. Solution1:

 ary1=ary
 newlist = [item for items in ary for item in items]
 x=[i for i in ary[0] if newlist.count(i)== len(ary1)]  

 #OUTPUT is x= [[0,4]]

Solution2:

x=[]    
for u in ary[0]:
    n=[]        
    n=[1 for t in range(1,len(ary)) if u in ary[t]] 
    if len(ary)-1==len(n):  
       x.append(u)

#OUTPUT is x= [[0,4]]

These two seem to take similar computational time when checked using line profiler. And this is the only point of heavy computation in my hundreds of liens of code and I want to reduce this. So, can you suggest any other Python commands/code that can do the task better than these two solutions?


Solution

  • You can try to convert each nested array at the second level into the set of tuples, where each lowest level array (i.e. [0,4]) is an element of the set. The conversion into tuples is required because lists are not hashable. Once you have each nested list of lists as a set, simply find their intersection.

    set.intersection(*[set(tuple(elem) for elem in sublist) for sublist in ary])