擅长:python、mysql、java
<p>@Taymon使用<em>list.index</em>得到的答案非常好。</p>
<p>FWIW,这里有一个使用<a href="http://docs.python.org/library/itertools.html#module-itertools">itertools module</a>的函数方法。它可以处理任何iterable输入,而不仅仅是列表:</p>
<pre><code>>>> from itertools import compress, count, imap, islice
>>> from functools import partial
>>> from operator import eq
>>> def nth_item(n, item, iterable):
indicies = compress(count(), imap(partial(eq, item), iterable))
return next(islice(indicies, n, None), -1)
</code></pre>
<p>这个例子很好,因为它展示了如何有效地组合Python的功能工具集。注意,一旦建立了管道,Python的eval循环就不会有任何变化——所有的事情都是以C速度完成的,内存占用很小,计算很慢,没有变量分配,组件可以单独测试。听着,这是函数式程序员梦寐以求的一切:-)</p>
<p>样本运行:</p>
<pre><code>>>> x = [False,True,True,False,True,False,True,False,False,False,True,False,True]
>>> nth_item(50, True, x)
-1
>>> nth_item(0, True, x)
1
>>> nth_item(1, True, x)
2
>>> nth_item(2, True, x)
4
>>> nth_item(3, True, x)
6
</code></pre>