如何更好地控制 Python 中的循环增量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4930404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:12:00  来源:igfitidea点击:

How do get more control over loop increments in Python?

pythonsyntax

提问by efficiencyIsBliss

I'm trying to loop from 0 to 1 using step sizes of 0.01 (for example). How would I go about doing this? The for i in range(start, stop, step)only takes integer arguments so floats won't work.

我正在尝试使用 0.01 的步长(例如)从 0 循环到 1。我该怎么做呢?该for i in range(start, stop, step)只需要整数参数,以便彩车将无法正常工作。

采纳答案by Santa

for i in [float(j) / 100 for j in range(0, 100, 1)]:
    print i

回答by efficiencyIsBliss

Well, you could make your loop go from 0 to 100 with a step the size of 1 which will give you the same amount of steps. Then you can divide i by 100 for whatever you were going to do with it.

好吧,你可以让你的循环从 0 到 100,步长为 1,这会给你相同的步数。然后你可以将 i 除以 100,无论你打算用它做什么。

回答by carl

One option:

一种选择:

def drange(start, stop, step):
    while start < stop:
            yield start
            start += step

Usage:

用法:

for i in drange(0, 1, 0.01):
    print i

回答by WombatPM

Avoid compounding floating point errors with this approach. The number of steps is as expected, while the value is calculated for each step.

避免使用这种方法复合浮点错误。步数与预期一致,同时计算每个步的值。

def drange2(start, stop, step):
    numelements = int((stop-start)/float(step))
    for i in range(numelements+1):
            yield start + i*step
Usage:

for i in drange2(0, 1, 0.01):
    print i

回答by Ganapathy Ramadass

your code

你的代码

for i in range(0,100,0.01):

can be achieved in a very simple manner instead of using float

可以以非常简单的方式实现,而不是使用浮动

for i in range(0,10000,1):

if you are very much concerned with float then you can go with https://stackoverflow.com/a/4935466/2225357

如果您非常关心浮动,那么您可以使用 https://stackoverflow.com/a/4935466/2225357

回答by Ganapathy Ramadass

you can use list comprehensions either:

您可以使用列表推导式:

print([i for i in [float(j) / 100 for j in range(0, 100, 1)]])

if you want control over printing i then do something like so:

如果你想控制打印我然后做这样的事情:

print(['something {} something'.format(i) for i in [float(j) / 100 for j in range(0, 100, 1)]])

or

或者

list(i for i in [float(j) / 100 for j in range(0, 100, 1)])

回答by user2538077

I would say the best way is using numpy array.

我会说最好的方法是使用 numpy 数组。

If you want to to loop from -2 thru +2 with increment of 0.25 then this is how I would do it:

如果您想以 0.25 的增量从 -2 到 +2 循环,那么我将这样做:

Start = -2
End = 2
Increment = 0.25
Array =  np.arange(Start, End, Increment)

for i in range(0, Array.size):
    print (Array[i])