简体   繁体   中英

range() with float step argument [duplicate]

Possible Duplicate:
Python decimal range() step value

I would like generate list like this:

[0, 0.05, 0.1, 0.15 ... ]

range(0, 1, 0.05) would be great but it doesn't work beacuse:

range() integer step argument expected, got float.

Have you any elegant idea? ;)

If you can use numpy, it's a good idea to use numpy.linspace . Functions that try to fit range logic on floating-point numbers, including numpy's own arange , usually get confusing regarding whether the end boundary ends up in the list or not. linspace elegantly resolves that by having you to explicitly specify the start point, the end point, and the desired number of elements:

>>> import numpy
>>> numpy.linspace(0.0, 1.0, 21)
array([ 0.  ,  0.05,  0.1 ,  0.15,  0.2 ,  0.25,  0.3 ,  0.35,  0.4 ,
        0.45,  0.5 ,  0.55,  0.6 ,  0.65,  0.7 ,  0.75,  0.8 ,  0.85,
        0.9 ,  0.95,  1.  ])

In Python 3, range returns a generator (immutable sequence)... so I think we can define a very simple function like:

def frange(start,stop, step=1.0):
    while start < stop:
        yield start
        start +=step

So:

for x in frange(0, 1, 0.05):
   print(x)

Python doesn't need to be tricky.

If you want a list, just call:

list(frange(0,1,0.05))

Or change the function to return a list right away.

You can use one line solutions that multiply or do other stuff, but it can be tricky with different start and end values. If you use this kind of ranges frequently, just use the function and reuse it. Even a one-liner repeated many times on code is bad.

或者这个怎​​么样:

[v*0.05 for v in range(0,int(1/0.05))]

How about this:

temp = range(0,100,5) # 0,5,10,...,95
final_list = map(lambda x: x/100.0,temp) # becomes 0,0.05,0.10,...,0.95

It's not very elegant, but I've never bothered into making a proper function. Also, it only works if the step size is rational. The advantage is that it's quick enough to be done on the spot.

See comments to your OP for a more general and more elegant solution.

What's wrong with

[i/100.0 for i in range(0, 100, 5)]

? You check how many digits you want (here two) and whip out a suitable multiplier (1 becomes 100, 0.05 becomes 5).

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