简体   繁体   English

在while循环中使用枚举函数

[英]Using enumerate function in while loops

I have several mathematical algorithms that use iteration to search for the right answer. 我有几个使用迭代来搜索正确答案的数学算法。 Here is one example: 这是一个例子:

def Bolzano(fonction, a, b, tol=0.000001):
    while abs(b - a) > tol:
        m = (a + b) / 2
        if sign(fonction(m)) == sign(fonction(a)):
            a = m
        else:
            b = m
    return a, b

I want to count how many times the algorithm goes through the loop to get a and b . 我想计算算法通过循环得到ab的次数 However this is not a for function and it isn't a list, so I can't clearly indicate what objects do I want to count if I use enumerate . 但是这不是for函数而且它不是列表,所以如果我使用enumerate ,我无法清楚地指出我想要计算的对象。 Is there a way to count those loops? 有没有办法计算这些循环?

Note: I am not trying to change the code itself. 注意:我不是要尝试更改代码本身。 I am really searching for a way to count iterations in a while loop, which I can then use for other cases. 我正在寻找一种在while循环中计算迭代的方法,然后我可以将其用于其他情况。

For a counter I use count from itertools : 对于计数器,我使用来自itertools count

from itertools import count
c = count(1)
>>>next(c)
1
>>>next(c)
2

and so on... 等等...

Syntax 句法

count(start=0, step=1)

Docs 文件

Make an iterator that returns evenly spaced values starting with number start. 创建一个迭代器,返回以数字start开头的均匀间隔值。

Ref. 参考。 itertools.count itertools.count

The simplest answer if you need a counter outside of a for loop is to count manually using a simple variable and addition inside your while loop: 如果你需要一个for循环之外的计数器,最简单的答案是使用一个简单的变量手动计数并在你的while循环中添加:

count = 0
while condition:
    ...
    count += 1

There is an alternative case - if each step of your iteration has a meanigful value to yield , you may want your loop to be a generator , and then use for loop and enumerate() . 还有另一种情况 - 如果迭代的每一步都有一个有意义的yield值,你可能希望你的循环是一个生成器 ,然后使用for循环和enumerate() This makes most sense where you care about which step you are on, not just the count at the end. 在你关心自己走向哪一步,而不仅仅是最后的计数时,这是最有意义的。 Eg: 例如:

def produce_steps():
    while condition:
        ...
        yield step_value

for count, step_value in enumerate(produce_steps()):
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM