JoeyHoward988
JoeyHoward988

Reputation: 31

Removing duplicate arrays in an array list python

I have been trying to remove duplicate arrays in my array list (ie. [[2,1],[1,2]) I want to get rid of only one of the arrays. I tried to reverse the list to and remove the duplicates but that does not work.

def grf_to_edge_list(file):
    edgelist = []
    for line in file:
        y = line.split()
        for i in range(3,len(y)):
            edgelist.append([int(y[0]),int(y[i])])
    for i in range(len(edgelist)-1):
        temp = edgelist[i]
        temp.reverse()
        if temp in edgelist:
            edgelist.remove(temp)
            i = i - 1
    return edgelist    

Here is the exact data:

1 2.0 1.0 2 3
2 1.0 0.0 1 3
3 0.0 2.0 1 2 4
4 3.0 3.0 3
5 3.0 0.0 

Upvotes: 0

Views: 196

Answers (2)

Ganesh Jadhav
Ganesh Jadhav

Reputation: 802

You might as well not add them to the list in first place, if you want to remove them later stage.

def grf_to_edge_list(file):
    edgelist = []
    for line in file:
        y = line.split()
        for i in range(3,len(y)):
            if [int(y[i]),int(y[0])] not in edgelist:    #My change is here.
                edgelist.append([int(y[0]),int(y[i])])
    return edgelist  

Upvotes: 1

Aaj Kaal
Aaj Kaal

Reputation: 1304

def new_grf_to_edge_list(file):    
    edgelist = []
    for line in file:
        y = line.split()
        for i in range(3,len(y)):
            edgelist.append([int(y[0]),int(y[i])])
    for i in range(len(edgelist)-1, 0, -1): # start from last item
        temp = copy.deepcopy(edgelist[i]) # deepcopy so that reverse does not change original
        temp.reverse()
        if temp in edgelist:
            edgelist.pop(i) # remove the item at i and not the one which is found
    return edgelist 

Please note the two changes. You cannot remove the temp because you are looping through the list. len(edgelist) changes. So if you loop from last-item you can remove it if it is found elsewhere since we are no longer going to access it(last-item in the loop).

Upvotes: 0

Related Questions