擅长:python、mysql、java
<p>如果您没有几个键,您可以在O(n)时间内执行此操作,例如使用<a href="https://en.wikipedia.org/wiki/Bucket_sort" rel="nofollow noreferrer">bucket sort</a>之类的东西:</p>
<pre><code>import pprint
from collections import defaultdict
from itertools import chain
# create buckets
buckets, no_key = defaultdict(list), {}
for i, d in enumerate(data):
if 'key' in d:
buckets[d['key']].append(d)
else:
no_key[i] = d
# create one sorted list for elements with keys, basically iterate over the buckets in ORDER
chained = list(chain.from_iterable([buckets[key] for key in ORDER]))[::-1]
# combine the two iterables, chained and no_key into the final result
final = [no_key.pop(i) if i in no_key else chained.pop() for i in range(len(data))]
pprint.pprint(final)
</code></pre>
<p><strong>输出</strong></p>
<pre><code>[{'data': 0},
{'data': 2, 'key': 'bar'},
{'data': 5, 'key': 'bar'},
{'data': 3},
{'data': 6, 'key': 'bar'},
{'data': 1, 'key': 'foo'},
{'data': 4, 'key': 'foo'},
{'data': 7}]
</code></pre>