I agree that if you have control over the format of the list, it's going to be a lot easier to sort them in the manner you want using
Bong's tip. Unfortunately, sometimes you don't have the luxury of designing the data format.
Equally unfortunate, there's no obvious way of doing this kind of sorting in Tcl. The best way I've been able to figure out transforms the list into an array and back for speed and simplicity. Here's what I did:
[tt]%
[ignore]for {set i 0} {$i < 10} {incr i} {
lappend coords [expr {2000.0*rand()-1000}] [expr {2000.0*rand()-1000}]
}[/ignore]
%
puts $coords
893.827048081 551.197095565 -30.414836961 817.835195837 -643.863575367 584.888803579 226.12175775 428.382511916 -175.122230861 720.665920396 232.124090768 -690.406454583 338.717825403 830.491545531 71.4057428164 116.3195144 982.078513122 -206.42995518 531.743289685 -990.530268285
%
array set tempcoords $coords
%
[ignore]foreach x [lsort -real [array names tempcoords]] {
lappend newcoords $x $tempcoords($x)
}[/ignore]
%
puts $newcoords
-643.863575367 584.888803579 -175.122230861 720.665920396 -30.414836961 817.835195837 71.4057428164 116.3195144 226.12175775 428.382511916 232.124090768 -690.406454583 338.717825403 830.491545531 531.743289685 -990.530268285 893.827048081 551.197095565 982.078513122 -206.42995518[/tt]
The summary:
[ol][li]Use
array set to create an array from the coordinate list.[/li]
[li]Use
array names to retrieve a list of just the keys (the x coordinates, in this case).[/li]
[li]Sort the keys (x coordinates) using
lsort -real.[/li]
[li]Loop through the sorted keys and use
lappend to append the key and its corresponding value to the new, sorted list.[/li][/ol] - Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax