Wednesday, June 26, 2019

#1 2019-01-11 03:22:25 am

Adam239
Member
Registered: 2016-10-14
Posts: 80

Repeat Item in List x Number of Times

I have a basic question re. Lists

If I have a list
set example to {a,b,c,d,e}

And I want to create a new list, with each item in example list repeated x number of times, is there an easy way to do this?

So, if x = 3, then new_list would be {a,a,a,b,b,b,c,c,c,d,d,d,e,e,e,}


running Sierra 10.12.5

Offline

 

#2 2019-01-11 03:58:19 am

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 4884

Re: Repeat Item in List x Number of Times

Hi.

Fairly easy:

Applescript:

set example to {"a", "b", "c", "d", "e"}
set x to 3

set new_list to repeatListItems(example, x)

on repeatListItems(originalList, x)
   set newList to {}
   repeat with thisItem in originalList
       set thisItem to thisItem's contents -- Resolve the reference.
       repeat x times
           set end of newList to thisItem
       end repeat
   end repeat
   
   return newList
end repeatListItems


NG

Offline

 

#3 2019-01-11 06:36:45 am

Adam239
Member
Registered: 2016-10-14
Posts: 80

Re: Repeat Item in List x Number of Times

Thats brilliant, thank you!
Really struggled to get my head around this one, and learnt a couple of new things from that solution, too.


running Sierra 10.12.5

Offline

 

#4 2019-01-11 07:54:54 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 86

Re: Repeat Item in List x Number of Times

In reading and learning about Applescript, I often see Nigel's script written as follows:

Applescript:

set example to {"a", "b", "c", "d", "e"}
set x to 3

set new_list to repeatListItems(example, x)

on repeatListItems(originalList, x)
   set newList to {}
   repeat with i from 1 to (count originalList)
       set thisItem to (item i of originalList)
       repeat x times
           set end of newList to thisItem
       end repeat
   end repeat
   
   return newList
end repeatListItems

Is one method or the other preferable in some way or is this simply a matter of style? Thanks.

Offline

 

#5 2019-01-11 08:51:53 am

Nigel Garvey
Moderator
From:: Warwickshire, England
Registered: 2002-11-20
Posts: 4884

Re: Repeat Item in List x Number of Times

peavine wrote:

Is one method or the other preferable in some way or is this simply a matter of style? Thanks.


In this particular case, it's simply what occurred to me as I was writing the script.  smile  Either form will do here. If the original list contained hundreds or thousands of items, I might do a bit more experimenting to see if either was more conducive to being sped up!


NG

Offline

 

#6 2019-01-11 08:57:36 am

peavine
Member
From:: Prescott, Arizona
Registered: 2018-09-04
Posts: 86

Re: Repeat Item in List x Number of Times

Thanks Nigel; I appreciate the response.

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)