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

这表示step参数不能为零:

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

当前回答

与R的seq函数类似,这个函数在给定正确的步长值的情况下以任意顺序返回一个序列。最后一个值等于停止值。

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([])

结果

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]

其他回答

你可以使用这个函数:

def frange(start,end,step):
    return map(lambda x: x*step, range(int(start*1./step),int(end*1./step)))

Range()只能处理整数,不能处理浮点数。

使用一个列表推导式来获得一个步骤列表:

[x * 0.1 for x in range(0, 10)]

更一般地说,生成器理解最小化内存分配:

xs = (x * 0.1 for x in range(0, 10))
for x in xs:
    print(x)

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

我会说使用while循环:

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

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

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

我的答案与使用map()的其他人类似,不需要NumPy,也不使用lambda(尽管您可以)。以dt为单位获取从0.0到t_max的浮点值列表:

def xdt(n):
    return dt*float(n)
tlist  = map(xdt, range(int(t_max/dt)+1))