擅长:python、mysql、java
<p>首先定义一个键函数,它在给定一个动作时返回阶段,例如</p>
<pre><code>key = lambda action: action["phase"]
</code></pre>
<p>现在先按<code>key</code>排序,这样不会重新排列顺序,即每个阶段的顺序都是守恒的(它是“<a href="http://wiki.python.org/moin/HowTo/Sorting/#Sort_Stability_and_Complex_Sorts" rel="nofollow">stable</a>”),然后使用<code>itertools</code>中的<a href="http://docs.python.org/library/itertools.html#itertools.groupby" rel="nofollow">^{<cd2>}</a>,如下所示:</p>
^{pr2}$
<p>如你所见,我把单子倒过来了。这样你就可以高效地跳出列表的末尾,而不是在deque上使用popleft。如果你愿意的话,把它们变成deque而不是反转。现在这样使用:</p>
<pre><code>for phase, actions in results:
while actions:
action = actions.pop()
# etc...
</code></pre>