简体   繁体   中英

Remove list from list of lists if condition is met

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?

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]]

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM