Arat254
Arat254

Reputation: 469

Iterating through multidimensional arrays in python

I have a 2d array in the following format:

[[a,b,c], [a], [c,d], [e]]

My objective is to identify all sublists of length 1 and compare the element in that sublist to elements of other sublists. If the element exists, remove both elements from the list.

In this case we look for 'a' in the 2d array and eliminate 'a,b,c' and 'a' from the 2d array.

The result should be:

[[c,d], [e]]

My code is as follows:

templist = list1 #list1 is the list containing all elements
for i in templist:
    if (len(i) == 1):
        if(any(i[0] in templist)):
            templist.remove(i)
            templist.remove([sublist for sublist in mylist if i[0] in sublist])
return templist

On running this code, I get the error - 'bool' object is not iterable. What I am doing wrong and how I can fix my error?

Upvotes: 0

Views: 430

Answers (1)

arshovon
arshovon

Reputation: 13651

Here is a way how you can achieve this:

Python 3 solution:

ar = [["a","b","c"], ["a"], ["c","d"], ["e"]]
for pos,inner_ar in enumerate(ar):
    if len(inner_ar)==1:
        for i,inner_ar2 in enumerate(ar):
            if i!=pos and any(c for c in inner_ar2 for c in inner_ar):
                del ar[pos]
                del ar[i]
print(ar)

Output:

[['c', 'd'], ['e']]

N.B.: Improvement can be done.

Upvotes: 1

Related Questions