Calling a generator multiple times

Steven Majewski sdm7g at Virginia.EDU
Thu Dec 6 22:02:20 CET 2001


On Thu, 6 Dec 2001, Bruce Eckel wrote:

> I'm trying to create a clever way to call a generator multiple
> times, but the only thing I've been able to come up with is:
>
> import random
> rgen = random.Random()
> def itemGenerator(dummy):
>   return rgen.choice(['one', 'two', 'three', 'four'])
>
> print map(itemGenerator, [None]* 25)
>
> This works, but it requires the 'dummy' argument which seems
> inelegant. I'll bet someone has a better idea...

Somebody already mentioned list comprehensions.

For clarity, I'ld probably define the function without the dummy
variable, and then use a lambda expression to add a dummy back again:

def itemGenerator(): ...

 map( lambda dummy: itemGenerator(), [None]*25 )


Another thing is just use random.Random().choice on copies of the
items:

  map( random.Random().choice,  [ item-list ]*25 )

or if you need to keep the random generator around for more:

  rgen = random.Random()
  map( rgen.choice, [ item-list ]*25 )


or if you're doing this alot, maybe just define your function to
take a collection and an optional number:

def itemGenerator( collection, n=1 ):
	if n == 1:
		return rgen.choice(collection)
	else:
		return map( rgen.choice, [collection]*n )

>>> itemGenerator(['one','two','three','four'])
 'four'
>>> itemGenerator(['one','two','three','four'], 10 )
['two', 'two', 'four', 'one', 'two', 'four', 'one', 'four', 'four', 'two']



-- Steve Majewski






More information about the Python-list mailing list