如何使用小数点范围()的步骤值? [英] How to use a decimal range() step value?
问题描述
我想我可以像下面这样做,但是失败了:
<$ c (0,1,0.1):
print i
相反,它表示step参数不能为零,这是我没有想到的。
解决方案 您也可以使用 NumPy 库(它不是标准库的一部分,但相对容易获得) c $ c> arange 函数:
>>> import numpy as np
>>> np.arange(0.0,1.0,0.1)
数组([0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])
以及 linspace
函数可以让您控制端点(非当事物不会总是分成正确的片数时):
>> ;> np.linspace(0,1,11)
array([0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])$ b $ b>> > np.linspace(0,1,10,endpoint = False)
array([0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9])
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
Instead, it says that the step argument cannot be zero, which I did not expect.
You can also use the NumPy library (which isn't part of standard library but is relatively easy to obtain) which has the arange
function:
>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
as well as the linspace
function which lets you have control over what happens at the endpoint (non-trivial for floating point numbers when things won't always divide into the correct number of "slices"):
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
这篇关于如何使用小数点范围()的步骤值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!