按给定的自定义顺序对列表排序

时间:2015-11-24 18:05:12

标签: python sorting

我有一个元组列表

x = [('U', 3), ('R', 3)]

我想按每个元组的第一个元素('U'或'R')的自定义顺序对列表进行排序

订单应该是:

order = ["R", "D", "L", "U"]

所以我的例子的输出将是:

x = [('R', 3), ('U', 3)]

我怎样才能在最佳时间内完成这项工作? 感谢

2 个答案:

答案 0 :(得分:8)

//based on https://github.com/danvk/mocha-react
var fs = require('fs');
var babel = require('babel-core');
var origJs = require.extensions['.js'];

// A module that exports a single, stubbed-out React Component.
var reactStub = 'module.exports = require("react").createClass({render:function(){return null;}});';

// Should this file be stubbed out for testing?
function shouldStub(filename) {
  if (!global.reactModulesToStub) {
    return false;
  }

  // Check if the file name ends with any stub path.
  var stubs = global.reactModulesToStub;
  for (var i = 0; i < stubs.length; i++) {
    if (filename.substr(-stubs[i].length) == stubs[i]) {
      return true;
    }
  }
  return false;
}

// Transform a file via JSX/Harmony or stubbing.
function transform(filename) {
  if (shouldStub(filename)) {
    return reactStub;
  } else {
    var content = fs.readFileSync(filename, 'utf8');
    return babel.transform(content).code;
  }
}

// Install the compiler.
require.extensions['.js'] = function(module, filename) {
  // optimization: code in a distribution should never go through JSX compiler.
  if (filename.indexOf('node_modules/') >= 0) {
    return (origJs || require.extensions['.js'])(module, filename);
  }

  return module._compile(transform(filename), filename);
};

module.exports = {
  transform: transform,
  shouldStub: shouldStub
};

sorted(x, key=lambda x: order.index(x[0])) 将返回一个适当的可比较密钥(元组的第一个元素)

答案 1 :(得分:4)

如果输入很大,那么值得预先计算字典以进行快速元素位置查找:

order_map = {}
for pos, item in enumerate(order):
    order_map[item] = pos

sorted(x, key=lambda x: order_map[x[0]])