<p>下面是学习新Python技术的中间替代方法:</p>
<pre><code>import itertools as it
def span_sum(iterable, start=6, end=7):
"""Return the sum of values found between start and end integers."""
iterable = iter(iterable)
flag = [True]
result = []
while flag:
result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
flag = list(it.dropwhile(lambda x: x!=end, iterable))
iterable = iter(flag)
next(iterable, [])
return sum(result)
# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18
</code></pre>
<p>原则上,此函数过滤输入,将值收集到满足您的条件的<code>result</code>中,并删除其余值,然后返回总和。您尤其可以观察以下技巧:</p>
<ul>
<li><a href="https://www.tutorialspoint.com/python/list_extend.htm" rel="nofollow noreferrer">extending</a>列表</li>
<li><a href="https://docs.python.org/3/library/itertools.html" rel="nofollow noreferrer">itertools</a>,例如<code>itertools.takewhile</code>,<code>itertools.dropwhile</code></li>
<li><a href="http://nvie.com/posts/iterators-vs-generators/" rel="nofollow noreferrer">iterators and generators</a></li>
<li><a href="https://www.programiz.com/python-programming/methods/built-in/next" rel="nofollow noreferrer">^{<cd4>}</a>函数和默认值</li>
<li><a href="https://www.programiz.com/python-programming/methods/built-in/sum" rel="nofollow noreferrer">^{<cd5>}</a>函数</li>
<li><a href="https://www.tutorialspoint.com/python/assertions_in_python.htm" rel="nofollow noreferrer">assertion testing</a></li>
</ul>