Idiomatic way of repeating items in a sequence.
Duncan Booth
duncan at NOSPAMrcp.co.uk
Mon Jun 30 10:36:46 EDT 2003
Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in
news:Xns93AA81EC76E7Eduncanrcpcouk at 127.0.0.1:
> The most obvious one that springs to mind is just a slight
> simplification of your version:
>
> def repeatitems(sequence, repetitions):
> newlist = []
> for item in sequence:
> newlist.extend([item] * repetitions)
> return newlist
>
Or, if you are in a "I've got a new toy to play with" mood you could use
itertools from Python 2.3 to obfuscate it somewhat:
from itertools import chain, izip, repeat
def repeatiterate(sequence, repetitions):
return chain(*izip(*repeat(sequence, repetitions)))
This version returns an iterator, so you might want to throw in a call to
'list' if you want to do anything other than iterating over the result.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list