How to use a decimal range() step value?

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

    I know I'm late to the party here, but here's a trivial generator solution that's working in 3.6:

    def floatRange(*args):
        start, step = 0, 1
        if len(args) == 1:
            stop = args[0]
        elif len(args) == 2:
            start, stop = args[0], args[1]
        elif len(args) == 3:
            start, stop, step = args[0], args[1], args[2]
        else:
            raise TypeError("floatRange accepts 1, 2, or 3 arguments. ({0} given)".format(len(args)))
        for num in start, step, stop:
            if not isinstance(num, (int, float)):
                raise TypeError("floatRange only accepts float and integer arguments. ({0} : {1} given)".format(type(num), str(num)))
        for x in range(int((stop-start)/step)):
            yield start + (x * step)
        return
    

    then you can call it just like the original range()... there's no error handling, but let me know if there is an error that can be reasonably caught, and I'll update. or you can update it. this is StackOverflow.

提交回复
热议问题