简体   繁体   中英

Generators in python

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?

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

BTW: nice reference on what you can do with generators in Python: https://wiki.python.org/moin/Generators

You can convert a generator to a list using:

list(float_range(1, 4, 0.1))

But seeing you are using matplotlib, you should be using numpy's solution instead:

np.arange(1, 4, 1, dtype=np.float64)

or:

np.linspace(start, stop, (start-stop)/step)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM