TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

Sorting with order arrays

1 点作者 fayyazkl超过 12 年前

1 comment

dalke超过 12 年前
This is done with a straight decorate-sort-undecorate (<a href="http://en.wikipedia.org/wiki/Schwartzian_transform" rel="nofollow">http://en.wikipedia.org/wiki/Schwartzian_transform</a>). In the simplest case, and in Python:<p><pre><code> "".join(sorted("ccbaba", key=lambda c: "cba".index(c))) </code></pre> gives "ccbbaa" as the result.<p>The performance is a function of the query string length and the order string length, because str.index is a linear search. The obvious speedup, should the order string be extremely long, is to turn the order string into a lookup table:<p><pre><code> order = {c: i for i, c in enumerate("bca")} "".join(sorted("ccbaba", key=lambda c: order[c]))</code></pre>