擅长:python、mysql、java
<blockquote>
<p>Warning: do not use the split string method.</p>
</blockquote>
<p>因此<code>groupby</code>/<code>islice</code>中的<code>itertools</code>应该可以工作:</p>
<pre><code>from itertools import groupby, islice
def kth_word(s, k):
g = (j for i, j in groupby(s, key=lambda x: x==' ') if not i)
return ''.join(next(islice(g, k-1, k), ''))
words = 'Alea iacta est'
res = kth_word(words, 2) # 'est'
</code></pre>
<p>我们通过将<code>StopIteration</code>中的可选参数设置为<code>''</code>来处理<code>StopIteration</code>错误。在</p>