Counting specific items in a list...

Hello,

I’d like to know if it’s possible to count only specific items in a list of integers. Let’s say I made a list, like {34, 0, 12, 142, 0, 97}. I want to count how many “0’s” are in the list (so the result is 2, in the example).

Is this possible? Thanks.

Carl,

The quickest way I could think to do this was using the below code - there may be a scripting addition that could help you out…

Hope that was some help!

Tom

my countItemsInList(0, {34, 0, 12, 142, 0, 97})
--> 2

on countItemsInList(countThis, theList)
	set theCounter to 0
	repeat with i from 1 to (count of items of theList)
		if item i of theList = countThis then
			set theCounter to theCounter + 1
		end if
	end repeat
	return theCounter
end countItemsInList

Hi :slight_smile:

Here another way with the “text items delimiters” :

set Lst to {34, 0, 12, 142, 0, 97}
set Itm to 0
return my CountItms(Itm, Lst) 
--> 2

on CountItms(Itm, Lst)
	set text item delimiters of AppleScript to "|"
	set Txt to Lst as text
	set text item delimiters of AppleScript to ("|" & Itm & "|")
	set Lst to text items of ("|" & Txt & "|")
	set text item delimiters of AppleScript to ""
	return (length of Lst) - 1
end CountItms

:wink:

Bug note: the above line should read:

set text item delimiters of AppleScript to "||"

Test:

CountItms(0, {34, 0, 12, 0, 0, 97}) --> 3

That’s right Has… Thank you :wink:

This shows how to do it with user interaction:

set theList to {34, 0, 12, 142, 0, 97}
set theChoice to display dialog "Choose a number to count" default answer "0" with icon note
try
	set theZeros to text returned of theChoice as integer
on error errmsg
	display dialog errmsg buttons {"Cancel"} default button 1 with icon stop
end try
set newlist to {}
repeat with i from 1 to count of theList
	if item i of theList is in theZeros then
		copy i to the end of newlist
	end if
end repeat
if (count of newlist) > 1 then
	display dialog "The number " & theZeros & " appears " & (count of newlist) & " times in the list" with icon note
else if newlist is {} then
	display dialog "The number " & theZeros & " does not appear in the list" with icon note
else
	display dialog "The number " & theZeros & " appears " & (count of newlist) & " time in the list" with icon note
end if