擅长:python、mysql、java
<p>您可以使用一个状态指示器来了解您在之前低于阈值之后现在是否已经高于阈值。这将允许您在不使用索引(不是很Pythonic)的情况下继续操作:</p>
<pre><code>series = [1,1,3,3,1,5,1,8,3,4,1]
threshold = 2.0
below = True
for value in series:
nowAbove = value > threshold
if below and nowAbove:
# do something
print(value)
below = not nowAbove
# 3
# 5
# 8
</code></pre>
<P>如果你经常做这样的循环,你可能想考虑创建一个特殊的迭代器,它只返回应该触发动作的值(即在阈值触发中断):</p>
<pre><code>def breaks(iterable,condition,state=False):
for value in iterable:
if condition(value) == state: continue
state = not state
if state: yield value
series = [1,1,3,3,1,5,1,8,3,4,1]
threshold = lambda v: v > 2.0
for value in breaks(series,threshold):
# do something (only values to process will be returned)
print(value)
</code></pre>
<p><em>函数breaks()的状态参数允许您决定序列中的第一个条目是否被视为中断(例如,当从上一个序列的最后一个状态继续时)</em></p>