check if array element exist by index and remove the dublicates

Viewed 40

I have an array like this:

array1=[[a,b,c,d],
       [e,f,g,h],
       [k,l,m,d],
       [x,y,j,d],
       [p,r,s,z]]

and I want to an array like this:

array2=[[a,b,c,d],
       [e,f,g,h], 
       [p,r,s,z]]

For example, the array1[0][3]=d is uniq now.

Can you help, how I can write a program this in Python?

2 Answers

You could just keep track of what you have seen so far in a set and loop through the array. If there are not items from the sublist in the set (the intersection is the empty set), append it to the result and add its elements to the set.

seen = set()
result = []

for sub in array1:
    if not seen.intersection(sub):
        result.append(sub)
        for l in sub:
            seen.add(l)

Result:

[['a', 'b', 'c', 'd'], 
 ['e', 'f', 'g', 'h'], 
 ['p', 'r', 's', 'z']]

Another solution (without using a set) is to copy array1 to array2, iterate through rows and items of array1 and remove any row from array2 whose item(s) have been previously seen:

array2 = list(array1)
seen = []
for row in array1:
    for item in row:
        if item in seen:
            array2.remove(row)
            break
        seen.append(item)

print(array2)
#[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['p', 'r', 's', 'z']]
Related