[英]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:我有一个列表列表,其中包含一个索引和两个坐标 [i,x,y] 例如:
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.我想检查 L[i][1] 是否重复(如 i=0 和 i=1 的示例中的情况)并仅将具有最小 i 的列表保留在列表中。 In the example [2,0,1] would be removed and L would be:
在示例中 [2,0,1] 将被删除,L 将是:
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:保留一
set
我们已经看到的x
坐标,遍历按i
和 build 升序排序的输入列表和 output 列表,只添加我们还没有看到x
的子列表:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.