Re: Determining item number matching "x" in a list
Re: Determining item number matching "x" in a list
- Subject: Re: Determining item number matching "x" in a list
- From: Nigel Garvey <email@hidden>
- Date: Wed, 12 Mar 2003 02:08:23 +0000
Paul Berkowitz wrote on Tue, 11 Mar 2003 12:51:11 -0800:
>
On 3/11/03 12:10 PM, "Steve Cunningham" <email@hidden> wrote:
>
>
> I wonder if there is some trivial way to do this without writing a repeat
>
> loop that cycles through every value of the list looking for a match:
>
>
>
> I have a list, theList = {"a","b","c","etc"} and I want to know the item
>
> number of the item that matches a variable x. I need something like
>
>
>
> "get the item number of x in theList"
>
>
>
> which returns a if x = "a", 2 if x = "b" etc.
>
>
>
> Did I miss a page in the manual :-)
>
>
No. They have never (yet) implemented 'whose' clauses for AppleScript lists
>
and records, as applications can implement for application objects. It's
>
been probably the major enhancement request for over 10 years. Maybe
>
AppleScript 2.0 will have it. We can hope. In the meantime, you have to use
>
a repeat loop.
If the list is quite large, you can usually speed up the process by using
a binary search, though there are positions in all lists that a
straight-through loop will find more quickly. Here's a sketch from a
project I shelved last year. If you need case sensitivity, put the call
to the handler in a 'considering case' block.
on getIndex of theItem into theList
-- The braces are necessary when checking that the item
-- is 'in' the list, to enable nested lists to be found
set searchItem to {theItem}
if theList does not contain searchItem then return 0
-- A list variable in a script object, for speed of access to its
items
script o
property pList : theList
end script
-- If the item is in the list, use a binary search to locate it
set L to 1
set R to (count theList)
repeat until theItem is item L of o's pList
set L to L + 1
set M to (L + R) div 2
if searchItem is in (items L thru M of o's pList) then
set R to M
else
set L to M + 1
end if
end repeat
return L
end getIndex
-- Test:
set myList to {}
repeat with i from 1 to 2000
set the end of myList to "Fred"
end repeat
set item 1999 of myList to "b"
set x to "b"
getIndex of x into myList
--> 1999
NG
_______________________________________________
applescript-users mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/applescript-users
Do not post admin requests to the list. They will be ignored.