1

I have a list of lists containing an index and two coordinates, [i,x,y] eg:

    L=[[1,0,0][2,0,1][3,1,2]]

I want to check if L[i][1] is repeated (as is the case in the example for i=0 and i=1) and keep in the list only the list with the smallest i. In the example [2,0,1] would be removed and L would be:

    L=[[1,0,0][3,1,2]]

Is there a simple way to do such a thing?

mellejgr
  • 43
  • 5
  • It is probably easier to build up a new list without repeats than it is to mutate the old list so as to remove the repeats. You could assign the new list to the same variable if you want. This question is close to being a duplicate of [Removing duplicates in lists](https://stackoverflow.com/q/7961363/4996248) – John Coleman May 13 '20 at 20:58

2 Answers2

1

Keep a set of the x coordinates we've already seen, traverse the input list sorted by ascending i and build and output list adding only the sublists whose x we haven't seen yet:

L = [[1, 0, 0], [2, 0, 1], [3, 1, 2]]

ans = []
seen = set()
for sl in sorted(L):
  if sl[1] not in seen:
    ans.append(sl)
    seen.add(sl[1])

L = ans

It works as required:

L
=> [[1, 0, 0], [3, 1, 2]]
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0

There are probably better solution but you can do with:

i1_list=[] 
result_list=[] 
for i in L:
    if not i[1] in i1_list:
         result_list.append(i)
         i1_list.append(i[1])
 print(result_list) 
Renaud
  • 2,709
  • 2
  • 9
  • 24