Sort Points by Y in Python

Hi all,

how can a pointlist be sorted by Y Value?

Thanks

There are a number of ways, you could use rs.SortPoints() or something like the following:

#(assuming pts is a list of 3D points)
pts_sort_y = [item[1] for item in sorted([(pt.Y,pt) for pt in pts])]

I shared two of the methods I tend to implement here:

Thanks for the examples.

the List comprehension method is nice.

You don’t need the nested loop/list comprehension, can get there with just sorted():

181011_SortPointsByY_00.gh (4.1 KB)

2 Likes

Thanks a lot for this example…

i have a lot of problems to understand the key in the sort method.
Your example is easy to understand.

The key parameter defines what to sort by and the lambda is just an inline function (in this case, one that returns the Y component of a point). One can usually find good sources on Google for general Python patterns (like sorting etc): https://wiki.python.org/moin/HowTo/Sorting

The key parameter in list.sort() method specifies a function that will be called on each list item before making comparisons. If you want your own implementation for sorting , you can use key parameter as an optional parameter.

def keyArgs(args):
    return args[1]
numList = [('Five', '5'), ('Two', '2'), ('Four', '4'), ('One', '1'), ('Three','3')]
numList.sort(key=keyArgs)
print(numList)
1 Like