Generators in python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I just came across the problem that I could not use the built-in range() function of python for float values. So I decided to use a float-range function that I manually defined:

def float_range(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

Problem is: This function returns a generator object. Now I needed this range for a plot:

ax.hist(some_vals, bins=(float_range(some_start, some_stop, some_step)), normed=False)

This will not work due to the return type of float_range(), which is a generator, and this is not accepted by the hist() function. Is there any workaround for me except not using yield?

Answers

If you need to give a range, you can do either

ax.hist(some_vals, bins=(list(float_range(some_start, some_stop, some_step))), normed=False)

Or just make your float_range return a list:

def float_range(start, stop, step):
    result = []
    r = start
    while r < stop:
        result.append(r)
        r += step
    return result

https://wiki.python.org/moin/Generators https://wiki.python.org/moin/Generators

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/23989372/generators-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils