for循环中的变量步

vol*_*erd 21 python for-loop

我试图在0.01和10之间循环,但在0.01和0.1之间使用0.01作为步骤,然后在0.1和1.0之间使用0.1作为步骤,并且在1.0和10.0之间使用1.0作为步骤.

我编写了while循环代码,但想让它更加pythonic.

i = 0.01
while i < 10:
   # do something
   print i
   if i < 0.1:
       i += 0.01
   elif i < 1.0:
       i += 0.1
   else:
       i += 1
Run Code Online (Sandbox Code Playgroud)

这将产生

0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 2, 3, 4, 5, 6, 7, 8, 9
Run Code Online (Sandbox Code Playgroud)

Rob*_*obᵩ 21

特殊钱包生成器功能可能是正确的方法.这将有效地将无聊的部分(正确的数字列表)与有趣的部分(# do something在您的示例中)分开.

def my_range():
    for j in .01, .1, 1.:
        for i in range(1, 10, 1):
            yield i * j

for x in my_range():
    print x
Run Code Online (Sandbox Code Playgroud)


Tad*_*sen 3

您可以有一个嵌套循环,外部循环迭代精度,内部循环只是range(1,10)

for precision in (0.01, 0.1, 1):
    for i in range(1,10):
        i*=precision
        print(i)
Run Code Online (Sandbox Code Playgroud)

然而,在这种情况下,浮点数可能不起作用,因为这显示了像0.30000000000000004我的机器上一样的值,对于精确的十进制值,您需要使用该decimal模块:

import decimal
for precision in ("0.01", "0.1", "1"):
    for i in range(1,10):
        i*=decimal.Decimal(precision)
        print(i)
Run Code Online (Sandbox Code Playgroud)