Re: Sort a List with Integers & Letters
Re: Sort a List with Integers & Letters
- Subject: Re: Sort a List with Integers & Letters
- From: kai <email@hidden>
- Date: Mon, 2 Apr 2007 21:57:34 +0100
On 2 Apr 2007, at 21:23, Steven Valenti wrote:
I would like to sort a list of items that are currently strings.
Most contain integers but some will also have letters.
set TheList to {"1610G", "121ZB", "114", "13", "21124", "121FB",
"250G", "240.25", "1610", "15", "240 25", "240"}
My current routine will get the numbers in order but nothing is
done for the letters or if a string of letters is added it will
error. Does anyone already have a functional routine that sorts
items much like the Finder would or how do I get around that
letters are involved?
I'd try to avoid those string-to-integer coercions if you possibly
can, Steven (although I suspect you'd already like to). ;-)
Fortunately, from AppleScript 1.10 (Mac OS X version 10.4), a new
considering/ignoring attribute was added - allowing numeric strings
to be collated by their numeric value. So you might like to try
something like:
-------------
to sort_items from i
script o
property l : i
end script
considering case and numeric strings
repeat with i from 2 to count o's l
set v to o's l's item i
repeat with i from (i - 1) to 1 by -1
tell o's l's item i to if v < it then
set o's l's item (i + 1) to it
else
set o's l's item (i + 1) to v
exit repeat
end if
end repeat
if i is 1 and v < o's l's beginning then set o's l's item 1 to v
end repeat
end considering
end sort_items
set theList to {"1610G", "121ZB", "114", "13", "21124", "121FB",
"250G", "240.25", "1610", "15", "240 25", "240"}
sort_items from theList
theList --> {"13", "15", "114", "121FB", "121ZB", "240", "240 25",
"240.25", "250G", "1610", "1610G", "21124"}
-------------
on ListSorter(TheList)
set theSize to length of TheList
repeat with i from 1 to theSize
repeat with X from 2 to (theSize - i + 1)
set Value_1 to (item (X - 1) of TheList)
repeat
try
set Value_1 to (Value_1 as integer)
exit repeat
on error
set Value_1 to (items 1 thru -2 of Value_1) as string
end try
end repeat
set Value_2 to (item X of TheList)
repeat
try
set Value_2 to (Value_2 as integer)
exit repeat
on error
set Value_2 to (items 1 thru -2 of Value_2) as string
end try
end repeat
if Value_1 > Value_2 then
set temp to (item (X - 1) of TheList)
set (item (X - 1) of TheList) to (item X of TheList)
set (item X of TheList) to temp
end if
end repeat
end repeat
return TheList
end ListSorter
ListSorter(TheList)
---
kai
_______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden