GhPython : List and sorting

Hello; how i can sort the list ? when i choose e = len i get the first value only;
with print len i get them all

import rhinoscriptsyntax as rs
import Rhino as rh
from ghpythonlib import components as cp
import scriptcontext
import Grasshopper.DataTree as ghdt


pnts1 = rs.DivideCurve(Crv0,100,True,True)
pnts2 = rs.DivideCurve(Crv1,100,True,True)
pnts = pnts1+pnts2
cnvx = cp.ConvexHull(pnts)[0]
crv = rh.Geometry.PolylineCurve.TryGetPolyline(cnvx)
sgmts = rh.Geometry.Polyline.GetSegments(crv[1])
e = sgmts
for i in sgmts:
    #print i
    lc = rh.Geometry.Line.ToNurbsCurve(i)
    len = rh.Geometry.Curve.GetLength(lc)
    print len

Hi,

If you want to sort your segments by length, it can simply be done like this:

# Get the line lengths
lengths = [ln.From.DistanceTo(ln.To) for ln in sgmts] # ln not seg
# Sort the lines by their lengths
sorted_segs = [ln for _, ln in sorted(zip(lengths, sgmts))]

You don’t need to convert the lines to Nurbs curves. Instead you can simply measure the distance between their end points.
It’s also generally not recommended to use variable (or constant) names that are used by Python, like len, which is used to get the length of an iterable (i.e. len([list])).

2 Likes

Thank you
what is seg in your script?

image

Oops, should be ln not seg. Btw, ln stands for line.

1 Like

Hello,

This should work too, sorting the list without zipping or creating a second list.

sgmts.sort(key=lambda x: x.From.DistanceTo(x.To))
2 Likes

Thank you ; sorted_segs is a list but i can’t use reverse

Thanks
this don’t work

sorted_segs.reverse() doesn’t work?

Can probably be fixed like this:

list(sgmts).sort(key=lambda x: x.From.DistanceTo(x.To))

No ; i use this based on your code
sort_segs = [ln for _, ln in sorted(zip(lengths, sgmts))]
rev_segs = [ln for _, ln in reversed(zip(lengths, sort_segs))]


Don’t work

Oops… this??? With an optional reverse=True

sgmts=sorted(sgmts,key=lambda x: x.From.DistanceTo(x.To))
1 Like

Should be:
sorted_segs = [ln for _, ln in sorted(zip(lengths, sgmts))]
reversed(sorted_segs)

1 Like

Thanks yes this work

reversed(sorted(sgmts,key=lambda x: x.From.DistanceTo(x.To)))

1 Like