擅长:python、mysql、java
<p>如果可以假设数字总是整数,那么可以使用它们来索引值,就像这样(也可以通过sort而不是sorted来实现)</p>
<pre><code>groups = defaultdict(list)
max_id = -1
for name, idx in lst:
groups[idx].append(name)
if max_id < idx:
max_id = idx
result = [(name, idx) for idx in range(max_id, -1, -1) for name in sorted(groups.get(idx, []))]
# [('Mitchell Piker', 3), ('Luke Skywalker', 2), ('Paul George', 1), ('Phil Dam', 1)]
</code></pre>
<p>编辑:</p>
<pre><code>from collections import defaultdict
groups = defaultdict(list)
for name, idx in lst:
groups[idx].append(name)
[(name, idx) for idx in sorted(groups.keys())[::-1] for name in sorted(groups[idx])]
</code></pre>
<p>注意:如果你反对使用<code>groups.keys()</code>,你可以用<code>[x for x in groups]</code>来代替。。。你知道吗</p>