我如何在0和1之间迭代0.1步?

这表示step参数不能为零:

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

当前回答

More_itertools是一个第三方库,它实现了numeric_range工具:

import more_itertools as mit


for x in mit.numeric_range(0, 1, 0.1):
    print("{:.1f}".format(x))

输出

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

这个工具也适用于十进制和分数。

其他回答

增加循环的i的大小,然后在需要时减少它。

for i * 100 in range(0, 100, 10):
    print i / 100.0

编辑:老实说,我不记得为什么我认为这会在语法上工作

for i in range(0, 11, 1):
    print i / 10.0

这应该有期望的输出。

range()内置函数返回一个整数值序列,所以您不能使用它来执行十进制步骤。

我会说使用while循环:

i = 0.0
while i <= 1.0:
    print i
    i += 0.1

如果你好奇的话,Python正在将你的0.1转换为0,这就是为什么它告诉你参数不能为0。

令人惊讶的是,在Python 3文档中还没有人提到推荐的解决方案:

参见: linspace菜谱展示了如何实现适用于浮点应用程序的惰性版本的range。

一旦定义,recipe就很容易使用,不需要numpy或任何其他外部库,只需要numpy.linspace()这样的函数。注意,第三个num参数指定所需值的数量,而不是step参数,例如:

print(linspace(0, 10, 5))
# linspace(0, 10, 5)
print(list(linspace(0, 10, 5)))
# [0.0, 2.5, 5.0, 7.5, 10]

下面我引用了Andrew Barnert的完整Python 3配方的修改版本:

import collections.abc
import numbers

class linspace(collections.abc.Sequence):
    """linspace(start, stop, num) -> linspace object

    Return a virtual sequence of num numbers from start to stop (inclusive).

    If you need a half-open range, use linspace(start, stop, num+1)[:-1].
    """
    def __init__(self, start, stop, num):
        if not isinstance(num, numbers.Integral) or num <= 1:
            raise ValueError('num must be an integer > 1')
        self.start, self.stop, self.num = start, stop, num
        self.step = (stop-start)/(num-1)
    def __len__(self):
        return self.num
    def __getitem__(self, i):
        if isinstance(i, slice):
            return [self[x] for x in range(*i.indices(len(self)))]
        if i < 0:
            i = self.num + i
        if i >= self.num:
            raise IndexError('linspace object index out of range')
        if i == self.num-1:
            return self.stop
        return self.start + i*self.step
    def __repr__(self):
        return '{}({}, {}, {})'.format(type(self).__name__,
                                       self.start, self.stop, self.num)
    def __eq__(self, other):
        if not isinstance(other, linspace):
            return False
        return ((self.start, self.stop, self.num) ==
                (other.start, other.stop, other.num))
    def __ne__(self, other):
        return not self==other
    def __hash__(self):
        return hash((type(self), self.start, self.stop, self.num))

Start和stop是包含的,而不是一个或另一个(通常不包括stop),并且没有导入,并使用生成器

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, july 8 2017, 04:57:36) [MSC v.1900 64 . 位(AMD64)]

sign = lambda x: (1, -1)[x < 0]
def frange(start, stop, step):
    i = 0
    r=len(str(step).split('.')[-1])
    args=(start,stop,step)
    if not step :return []
    if all(int(i)==float(i) for i in args):
        start,stop,step=map(int,args)
    if sign(step)==1:
        while start + i * step < stop:
            yield round(start + i * step,r)
            i += 1
    else:
        while start + i * step > stop:
            yield round(start + i * step,r)
            i += 1