【问题标题】:Can you use a for loop to implement a sentinel controlled loop in Python?你可以使用 for 循环在 Python 中实现哨兵控制循环吗?
【发布时间】:2015-03-13 05:04:38
【问题描述】:

我不太确定是否可能有另一个重复,但根据主题提出问题。

这个问题的目的不是要弄清楚你是否应该使用for循环来实现哨兵控制。

而是看看它是否可以做到,从而更好地理解forwhile循环之间的区别。

【问题讨论】:

    标签: python


    【解决方案1】:

    使用itertools 是可能的:

    >>> import itertools
    >>>
    >>> SENTINEL = 0
    >>> for i in itertools.count():
    ....:    if SENTINEL >= 10:
    ....:        print "Sentinel value encountered! Breaking..."
    ....:        break
    ....:    
    ....:    SENTINEL = SENTINEL + 1
    ....:    print "Incrementing the sentinel value..."
    ....: 
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Incrementing the sentinel value...
    Sentinel value encountered! Breaking...
    

    (灵感来自堆栈溢出问题“Looping from 1 to infinity in Python”。)

    【讨论】:

    • itertools.count() 是做什么的?
    • 它返回一个迭代器,它是“表示数据流的对象。重复调用迭代器的 next() 方法会返回流中的连续项。” from python docs 。在这种情况下,流是无限的,我们用哨兵值打破循环。
    • 听起来像是一个相当大的解决方法,可以让 for 循环由哨兵控制。
    • 我并没有说这是个好主意,我只是向您展示了一种可行的方法:-)
    • 是的,正是我需要看到的。
    【解决方案2】:

    在不导入任何模块的情况下,您还可以使用for 进行“哨兵”控制循环,方法是将循环设置为无穷大,break 使用condition

    infinity = [0]
    sentinelValue = 1000
    for i in infinity:
        if i == sentinelValue:
            break
    
        # like a dog chasing the tail, we move the tail...
        infinity.append(i+1)
    
        print('Looped', i, 'times')
    
    print('Sentinel value reached')
    

    虽然这会创建一个非常大的无限列表,会消耗内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 2020-06-15
      • 1970-01-01
      相关资源
      最近更新 更多