擅长:python、mysql、java
<p>我并不推荐它,但是要使用<code>itertools.groupby()</code>来实现这一点,您需要一个能记住上次使用的键的键函数。像这样:</p>
<pre><code>def keyfunc(item, keys=[None]):
if item[0] != keys[-1] and not item[0].startswith(" "):
keys.append(item[0])
return keys[-1]
d = {k: [y for x in g for y in x[1:]] for k, g in groupby(lst, key=keyfunc)}
</code></pre>
<p>一个简单的<code>for</code>循环看起来更干净,不需要任何<code>import</code>s:</p>
^{pr2}$