我如何在0和1之间迭代0.1步?
这表示step参数不能为零:
for i in range(0, 1, 0.1):
print(i)
我如何在0和1之间迭代0.1步?
这表示step参数不能为零:
for i in range(0, 1, 0.1):
print(i)
当前回答
令人惊讶的是,在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))
其他回答
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)
import numpy as np
for i in np.arange(0, 1, 0.1):
print i
下面是我的解决方案,它可以很好地使用float_range(- 1,0,0.01),并且没有浮点表示错误。它不是很快,但工作得很好:
from decimal import Decimal
def get_multiplier(_from, _to, step):
digits = []
for number in [_from, _to, step]:
pre = Decimal(str(number)) % 1
digit = len(str(pre)) - 2
digits.append(digit)
max_digits = max(digits)
return float(10 ** (max_digits))
def float_range(_from, _to, step, include=False):
"""Generates a range list of floating point values over the Range [start, stop]
with step size step
include=True - allows to include right value to if possible
!! Works fine with floating point representation !!
"""
mult = get_multiplier(_from, _to, step)
# print mult
int_from = int(round(_from * mult))
int_to = int(round(_to * mult))
int_step = int(round(step * mult))
# print int_from,int_to,int_step
if include:
result = range(int_from, int_to + int_step, int_step)
result = [r for r in result if r <= int_to]
else:
result = range(int_from, int_to, int_step)
# print result
float_result = [r / mult for r in result]
return float_result
print float_range(-1, 0, 0.01,include=False)
assert float_range(1.01, 2.06, 5.05 % 1, True) ==\
[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01, 2.06]
assert float_range(1.01, 2.06, 5.05 % 1, False)==\
[1.01, 1.06, 1.11, 1.16, 1.21, 1.26, 1.31, 1.36, 1.41, 1.46, 1.51, 1.56, 1.61, 1.66, 1.71, 1.76, 1.81, 1.86, 1.91, 1.96, 2.01]
range()内置函数返回一个整数值序列,所以您不能使用它来执行十进制步骤。
我会说使用while循环:
i = 0.0
while i <= 1.0:
print i
i += 0.1
如果你好奇的话,Python正在将你的0.1转换为0,这就是为什么它告诉你参数不能为0。
下面是一个使用itertools的解决方案:
import itertools
def seq(start, end, step):
if step == 0:
raise ValueError("step must not be 0")
sample_count = int(abs(end - start) / step)
return itertools.islice(itertools.count(start, step), sample_count)
使用的例子:
for i in seq(0, 1, 0.1):
print(i)