Calling a generator multiple times
Alex Martelli
aleax at aleax.it
Sat Dec 8 17:50:23 EST 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...
Why not just:
def itemChooser(): return rgen.choice(('one','two','three','four'))
print [itemChooser() for i in range(25)]
(In Python 2.2 and later, 'generator' is a specific term, used in "from
__future__ import" in particular, for a function containing keyword 'yield'
and thus returning an iterator; like other terms that get hijacked by some
programming language for specific meanings, such as "module", "function",
"type", etc, it's thus best avoided in its non-specific wider sense:-).
Alex
More information about the Python-list
mailing list