[Newbie] List from a generator function
Peter Otten
__peter__ at web.de
Sun Jul 23 05:17:16 EDT 2006
Ernesto García García wrote:
> I'm sure there is a better way to do this:
>
> [random.choice(possible_notes) for x in range(length)]
Note that "generator" has a fixed meaning in Python:
http://www.python.org/dev/peps/pep-0255/
For generators you can use
list(itertools.islice(gen()), length)
What you need then would be a way to turn an ordinary function into a
generator:
>>> def make_gen(fun, *args, **kw):
... def gen():
... while 1:
... yield fun(*args, **kw)
... return gen()
...
>>> from random import choice
>>> from itertools import islice
>>> length = 7
>>> sample = "abcde"
>>> list(islice(make_gen(choice, sample), length))
['e', 'b', 'b', 'a', 'b', 'b', 'a']
Peter
More information about the Python-list
mailing list