擅长:python、mysql、java
<p>与其更新索引并根据索引获取新元素,不如使用<a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow noreferrer"><strong>iteraor</strong></a>更像是Pythonic</em>:</p>
<pre class="lang-py prettyprint-override"><code>#list of sauce packs
saucePacks = iter(['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4'])
saucePack = next(saucePacks)
#list of pizzas
pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']
#iterating over strings
for pizza in pizzas:
if 'sauce_error' in pizza:
saucePack = next(saucePacks) # takes the next sauce from the list
print(saucePack, pizza)
</code></pre>
<p>请注意,当迭代器耗尽时,您需要小心(您还需要使用索引,以防它超过列表的大小…)</p>