How to use a decimal range() step value?

前端 未结 30 2135
醉话见心
醉话见心 2020-11-21 22:34

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
         


        
30条回答
  •  一生所求
    2020-11-21 23:26

    Similar to R's seq function, this one returns a sequence in any order given the correct step value. The last value is equal to the stop value.

    def seq(start, stop, step=1):
        n = int(round((stop - start)/float(step)))
        if n > 1:
            return([start + step*i for i in range(n+1)])
        elif n == 1:
            return([start])
        else:
            return([])
    

    Results

    seq(1, 5, 0.5)
    

    [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

    seq(10, 0, -1)
    

    [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

    seq(10, 0, -2)
    

    [10, 8, 6, 4, 2, 0]

    seq(1, 1)
    

    [ 1 ]

提交回复
热议问题