<p>我认为这些例子会帮助你做你想做的事情:</p>
<pre><code>lst = pots[0]
# solution using a for loop
for i, member in enumerate(lst):
# i is the position in the list
# member is the data item from the list
assert lst[i] == member # cannot ever fail
if member == the_one_we_want:
break # exit loop, variables i and member are set
else:
# the_one_we_want was never found
i = -1 # signal that we never found it
# solution using .index() method function on a list
try:
i = lst.index(the_one_we_want)
except ValueError:
# the_one_we_want was not found in lst
i = -1 # signal that we never found it
</code></pre>
<p>编辑:这些评论让我意识到,<code>for</code>循环中的<code>else</code>可能会让人困惑。你知道吗</p>
<p>在Python中,<code>for</code>循环可以有自己的<code>else</code>大小写。raymondhettinger评论说,他希望关键字是<code>when_no_break</code>这样的,因为您唯一使用这个<code>else</code>的时候是使用<code>break</code>关键字!你知道吗</p>
<p>如果<code>for</code>循环提前退出,则<code>break</code>代码不会运行。但是如果<code>for</code>循环一直运行到最后,并且没有<code>break</code>发生,那么在最后<code>else</code>代码运行。Nick Coghlan称之为“completion子句”,以区别于<code>if</code>语句中的“conditional else”。你知道吗</p>
<p><a href="https://ncoghlan_devs-python-notes.readthedocs.org/en/latest/python_concepts/break_else.html" rel="nofollow">https://ncoghlan_devs-python-notes.readthedocs.org/en/latest/python_concepts/break_else.html</a></p>
<p>有点不幸的是,<code>else</code>紧跟在<code>if</code>语句之后,因为这可能会让人困惑。那<code>else</code>与那<code>if</code>没有关系;它与<code>for</code>循环有关,这就是它缩进的原因。(我很喜欢在Python中,当它们一起运行时,您必须将它们排列起来。)</p>