首页 > 解决方案 > 根据步长调整for循环的范围

问题描述

我想请用户确定 for 循环的步长。用户将在输入中写入一个浮点数,例如0.2or 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 to 350 with step size 5这意味着我们乘以1或对于步长我们将它们3.5乘以。那么我们应该怎么做呢?1000.510

我的意思是当用户写入时,stepseize = 0.00005我们有十进制数,所以我们必须将和5乘以前面有零a,. 如果用户写我们有十进制数,我们必须乘以成13.515100000stepseize = 0.0042413.510000

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)

标签: pythonfor-loop

解决方案


您可以编写自己的范围生成器来包装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

推荐阅读