How to use a decimal range() step value?

2018-12-31 03:56发布

Is there a way to step between 0 and 1 by 0.1?

I thought I could do it like the following, but it failed:

for i in range(0, 1, 0.1):
    print i

Instead, it says that the step argument cannot be zero, which I did not expect.

30条回答
荒废的爱情
2楼-- · 2018-12-31 04:30

NumPy is a bit overkill, I think.

[p/10 for p in range(0, 10)]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

Generally speaking, to do a step-by-1/x up to y you would do

x=100
y=2
[p/x for p in range(0, int(x*y))]
[0.0, 0.01, 0.02, 0.03, ..., 1.97, 1.98, 1.99]

(1/x produced less rounding noise when I tested).

查看更多
听够珍惜
3楼-- · 2018-12-31 04:30
import numpy as np
for i in np.arange(0, 1, 0.1): 
    print i 
查看更多
忆尘夕之涩
4楼-- · 2018-12-31 04:30

My answer is similar to others using map(), without need of NumPy, and without using lambda (though you could). To get a list of float values from 0.0 to t_max in steps of dt:

def xdt(n):
    return dt*float(n)
tlist  = map(xdt, range(int(t_max/dt)+1))
查看更多
何处买醉
5楼-- · 2018-12-31 04:30

My solution:

def seq(start, stop, step=1, digit=0):
    x = float(start)
    v = []
    while x <= stop:
        v.append(round(x,digit))
        x += step
    return v
查看更多
与君花间醉酒
6楼-- · 2018-12-31 04:31

scipy has a built in function arange which generalizes Python's range() constructor to satisfy your requirement of float handling.

from scipy import arange

查看更多
笑指拈花
7楼-- · 2018-12-31 04:32

Building on 'xrange([start], stop[, step])', you can define a generator that accepts and produces any type you choose (stick to types supporting + and <):

>>> def drange(start, stop, step):
...     r = start
...     while r < stop:
...         yield r
...         r += step
...         
>>> i0=drange(0.0, 1.0, 0.1)
>>> ["%g" % x for x in i0]
['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']
>>> 
查看更多
登录 后发表回答