Search code examples
python-3.xlistalgorithmsortingfilter

what is the most efficient way to gather all points at a certain height?


I have a List[List[int]] that represents points [x,y]

points = [[1,2],[1,3],[2,1],[2,3]]

What is the most efficient way to gather-up all the points with a specific height ?

So if we want all points with a height of 3 ( y == 3 ) :

answer = [[1,3],[2,3]]

I'm assuming there is a more efficient way than this :

answer = []
for p in points:
    if p[1] == 3:
        answer.append(p)

Further, how to query the set of distinct heights that have at least one point ?

answer = [1,2,3]

Solution

  • I think you can use filter or list comprehension, as described in this question: How to return a subset of a list that matches a condition

    answer = [p for p in points if p[1] == 3]
    

    And to query the set of distinct heights that have at least one point, you could use Python's Set and iterate through the list, adding all heights. Sets don't allow duplicate values, so you'll get only distinct values.

    heightSet = {p[1] for p in points}
    

    If you want the result as list, just call list method.

    distinctHeightsList = list(heightSet)