擅长:python、mysql、java
<p>使用<a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer">enumerate</a>:</p>
<pre><code>listo = [[1,2], [3,4,5]]
res = next(i for i, sublist in enumerate(listo) if 3 in sublist)
print(res) # -> 1
</code></pre>
<p>请注意,Python是0索引语言;列表中的第一个元素的索引号为0。这就是为什么上面的代码返回<code>1</code>。如果您想获得<code>2</code>,那么,只需在其中添加<code>1</code>,或者更好地使用enumerate(<code>enumerate(listo, 1)</code>)的可选<code>start</code>参数。你知道吗</p>
<p>要使上述<em>防错</em><sup>1</sup>,可以指定在<code>3</code>不在任何子列表中时要返回的默认值。你知道吗</p>
<pre><code>res = next((i for i, sublist in enumerate(listo) if 3 in sublist), 'N\A')
</code></pre>
<hr/>
<p><sup>1</sup><code>next</code>引发<code>StopIteration</code>如果它在没有找到返回对象的情况下耗尽iterable,<strong>除非提供了默认值。你知道吗</p>