How to use a decimal range() step value?

前端 未结 30 2167
醉话见心
醉话见心 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:09

    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']
    >>> 
    

提交回复
热议问题