How to use a decimal range() step value?

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

    start and stop are inclusive rather than one or the other (usually stop is excluded) and without imports, and using generators

    def rangef(start, stop, step, fround=5):
        """
        Yields sequence of numbers from start (inclusive) to stop (inclusive)
        by step (increment) with rounding set to n digits.
    
        :param start: start of sequence
        :param stop: end of sequence
        :param step: int or float increment (e.g. 1 or 0.001)
        :param fround: float rounding, n decimal places
        :return:
        """
        try:
            i = 0
            while stop >= start and step > 0:
                if i==0:
                    yield start
                elif start >= stop:
                    yield stop
                elif start < stop:
                    if start == 0:
                        yield 0
                    if start != 0:
                        yield start
                i += 1
                start += step
                start = round(start, fround)
            else:
                pass
        except TypeError as e:
            yield "type-error({})".format(e)
        else:
            pass
    
    
    # passing
    print(list(rangef(-100.0,10.0,1)))
    print(list(rangef(-100,0,0.5)))
    print(list(rangef(-1,1,0.2)))
    print(list(rangef(-1,1,0.1)))
    print(list(rangef(-1,1,0.05)))
    print(list(rangef(-1,1,0.02)))
    print(list(rangef(-1,1,0.01)))
    print(list(rangef(-1,1,0.005)))
    # failing: type-error:
    print(list(rangef("1","10","1")))
    print(list(rangef(1,10,"1")))
    

    Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]

提交回复
热议问题