2

我想知道是否有一种优雅的方法可以检查是否可以检查在 while 循环中不断变化的值,如果值停止变化并保持不变,则停止 while 循环。

例如:

Value = 0
while True:
    value changes everytime
    (if value still the same break)
4

4 回答 4

5

这条路怎么样?顺便说一句:修复您的拼写错误while不在Whilepython 中。

value = 0
while True:
    old_value, value = value, way_to_new_value
    if value == old_value: break
于 2015-10-15T10:24:42.883 回答
2
previous = None
current = object()
while previous != current:
    previous = current
    current = ...
于 2015-10-15T10:30:54.680 回答
0

你可以:

value_old = 0
value_new = 1
value = [value_old, value_new]
while True:
    # change

    # test
    if value[0] == value[1]:
        break
    else:
        value = [value[1], value[0]]
于 2015-10-15T10:25:54.830 回答
0

一个更可移植的解决方案是将它设为一个类,以便实例保持先前的值。我还需要模糊匹配,因此我将其包含在下面的示例中。

class SamenessObserver:
    """An object for watching a series of values to see if they stay the same.
    If a fuzy match is required maxDeviation may be set to some tolerance.

    >>> myobserver = SamenessObserver(10)
    >>> myobserver.check(9)
    False
    >>> myobserver.check(9)
    True
    >>> myobserver.check(9)
    True
    >>> myobserver.check(10)
    False
    >>> myobserver.check(10)
    True
    >>> myobserver.check(11)
    False
    >>> myobserver = SamenessObserver(10, 1)
    >>> myobserver.check(11)
    True
    >>> myobserver.check(11)
    True
    >>> myobserver.check(10)
    True
    >>> myobserver.check(12)
    False
    >>> myobserver.check(11)
    True
    >>> 

    """

    def __init__(self, initialValue, maxDeviation=0):
        self.current = 0
        self.previous = initialValue
        self.maxDeviation = maxDeviation

    def check(self, value):
        self.current = value
        sameness = (self.previous - self.maxDeviation) <= self.current <= (self.previous + self.maxDeviation)
        self.previous = self.current
        return sameness
于 2018-12-07T16:56:56.487 回答