Paul Thomas
Paul Thomas

Reputation: 497

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. These P1, P2, P3, P4 and P5 represent a point location in space. I would like to remove points which are very close to each other, such as P4 and P5. Since P4 and P5 are very close to P1 and retain only their first occurrence in new list. The closeness of each points is checked using a function "is_equal" given below in full code.

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,

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

Can anyone suggest a better way to deal with such repetitive points deletion?

Upvotes: 0

Views: 66

Answers (1)

0e1val
0e1val

Reputation: 481

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)}

Upvotes: 2

Related Questions