Beginers question: split list group by 4

Hi,
I write simple script for parsing txt files.
This is input string: {“item1”, “item2”, “item3”, “item4”, “item5”, “item6”, “item7”, “item8”…}
How to get this output string: {{“item1”, “item2”, “item3”, “item4”}, {“item5”, “item6”, “item7”, “item8”}…}?

Help me please.

Those are lists, not strings.

Try something like this:

on splitList(n, someList)
	set output to {}
	
	repeat with i from 1 to (count someList) by n
		try
			set end of output to items i thru (i + n - 1) of someList
		on error
			set end of output to items i thru -1 of someList
		end try
	end repeat
	
	return output
end splitList

-- Example
splitList(4, {"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"})

Thank you. This handler works!

Hi Bruce,

I understand the reason for the on error, which is incase the split number (in this case 4) is a number greater than the number of items.

Can you explain the reason for the repeat loop , in you script I do not understand it’s inclusion and what the BY part is for?.

If I used the below script would there be a difference? I fear I am missing something obvious, so please forgive me if my question seems dumb. :rolleyes:

splitList(4, {"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", "item9"})
on splitList(n, someList)
	try
		set output to {items 1 thru n of someList}
		set end of output to items (1 + n) thru -1 of someList
	on error
		set output to {items 1 thru -1 of someList}
	end try
	return output
end splitList

Thanks

Mark

Use a 2 for each script (so I don’t have to post a longer example list :P) and compare the results:

-- Mine
{{"item1", "item2"}, {"item3", "item4"}, {"item5", "item6"}, {"item7", "item8"}, {"item9"}}

-- Yours
{{"item1", "item2"}, {"item3", "item4", "item5", "item6", "item7", "item8", "item9"}}

The by part increases the repeat variable (in this case, i) by that much on each loop (e.g., 1,5,9).

See also: repeat Statements

Ah, I see, :slight_smile:

Thanks for the explanation, and the link.

regards
Mark