简体   繁体   English

如何根据条件从列表列表中删除列表?

[英]How to remove a list from list of lists based on a condition?

I am trying to remove a list from a list of lists based on a condition. 我试图根据条件从列表列表中删除列表。 For example, pnts is the list of lists formed using lists such as P1, P2, P3, P4 and P5. 例如,pnts是使用诸如P1,P2,P3,P4和P5之类的列表形成的列表的列表。 These P1, P2, P3, P4 and P5 represent a point location in space. 这些P1,P2,P3,P4和P5表示空间中的点位置。 I would like to remove points which are very close to each other, such as P4 and P5. 我想删除彼此非常接近的点,例如P4和P5。 Since P4 and P5 are very close to P1 and retain only their first occurrence in new list. 由于P4和P5非常接近P1,因此仅将它们的第一次出现保留在新列表中。 The closeness of each points is checked using a function "is_equal" given below in full code. 使用下面以完整代码提供的函数“ is_equal”检查每个点的接近度。

P1 = [3.333, 0.000, 0.000]
P2 = [0.000, 0.000, 0.000]
P3 = [10.000, 0.000, 0.000]
P4 = [3.333, 0.000, 0.000]
P5 = [3.3, 0.000, 0.000]

pnts = [P1, P2, P3, P4, P5]

if the distance measured between two points are close to zero then the second duplicate point should be removed from the list. 如果两点之间测得的距离接近于零,则应从列表中删除第二个重复点。

so the answer should be, 所以答案应该是

pnts = [P1, P2, P3]

Full code is shown below, 完整代码如下所示,

import math
import collections
import itertools

def is_equal(grid1, grid2):
    L = math.sqrt((grid1[0]-grid2[0])**2 + (grid1[1]-grid2[1])**2 + (grid1[2]-grid2[2])**2)
    if round(L)==0:
        return True
    else:
        return False

P1 = [3.333, 0.000, 0.000]
P2 = [0.000, 0.000, 0.000]
P3 = [10.000, 0.000, 0.000]
P4 = [3.333, 0.000, 0.000]
P5 = [3.3, 0.000, 0.000]

pnts = [P1, P2, P3, P4, P5]

i tried with itertools groupby function but i could not get the right answer, that is, 我尝试使用itertools groupby函数,但是无法获得正确的答案,也就是说,

list(pnts for pnts,_ in itertools.groupby(pnts))

Can anyone suggest a better way to deal with such repetitive points deletion? 有人可以建议一种更好的方法来处理此类重复点删除吗?

Here is a block of code that does what you requested, however you might need to tune the precision point according to your needs 这是一段代码,可以完成您的要求,但是您可能需要根据需要调整精度点

P1 = [3.333, 0.000, 0.000]
P2 = [0.000, 0.000, 0.000]
P3 = [10.000, 0.000, 0.000]
P4 = [3.333, 0.000, 0.000]
P5 = [3.3, 0.000, 0.000]

pnts = [P1, P2, P3, P4, P5]

pnts_filteres = set([tuple([round(v, 1) for v in p]) for p in pnts])
print(pnts_filteres)

{(3.3, 0.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)} {(3.3,0.0,0.0),(0.0,0.0,0.0),(10.0,0.0,0.0)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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