Python 可根据步长调整for循环的范围
我想让用户确定for循环的步长。 用户将在输入中写入一个浮点数,例如Python 可根据步长调整for循环的范围,python,for-loop,Python,For Loop,我想让用户确定for循环的步长。 用户将在输入中写入一个浮点数,例如0.2或0.5,但Python不接受for循环中的浮点数,因此我们必须将其更改为整数 for i in range (1, 3.5, 0.5): #This is proposal print(i) for i in range (10, 35, 5): #This is the logical term for Python print(i/10) 如果用户写入0.05循环的范围必须是100到350,步长为5,
0.2
或0.5
,但Python不接受for循环中的浮点数,因此我们必须将其更改为整数
for i in range (1, 3.5, 0.5): #This is proposal
print(i)
for i in range (10, 35, 5): #This is the logical term for Python
print(i/10)
如果用户写入0.05
循环的范围必须是100到350,步长为5
,这意味着我们将1
和3.5
乘以100
,或者对于步长0.5
我们将它们乘以10
。那我们该怎么办呢
我的意思是当用户写入stepAck=0.00005
时,我们有5
十进制数,因此我们必须将1
和3.5
相乘成a1
,它前面有5
零,100000
。如果用户写入stepAck=0.0042
我们有4
十进制数,我们必须将1
和3.5
相乘成10000
q = 100... # zeroes are in terms of number of decimals
for i in range (1*(q), 3.5*(q), n*q) : #This is the logical term for Python
print(i/q)
您可以编写自己的范围生成器来包装
range()
函数,但处理浮动:
def range_floats(start,stop,step):
f = 0
while not step.is_integer():
step *= 10
f += 10
return (i / f for i in range(start*f,stop*f,int(step)))
有效的方法是:
>>> for i in range_floats(0, 35, 0.5):
... print(i)
...
0.0
0.5
1.0
.
.
.
33.5
34.0
34.5
我坚决建议使用numpy的
arange
,可能会重复。它的工作原理与range类似,但也可以处理浮动。如果您不想使用其他软件包,您将不得不处理“数字前面的许多零”。@offeltoffel谢谢,它是否比没有numpy的正常使用速度慢,或者它的速度没有差异?@David:numpy通常比普通python中的大多数数字例程都快。@offeltoffel非常感谢您。