当前位置:  开发笔记 > 编程语言 > 正文

自然排序算法

如何解决《自然排序算法》经验,为你挑选了4个好方法。

如何在不同的编程语言中自然地对字符串数组进行排序?发布您的实现以及答案中的语言.



1> jfs..:

以下是如何在Python中获得类似资源管理器的行为:

#!/usr/bin/env python
"""
>>> items = u'a1 a003 b2 a2 a10 1 10 20 2 c100'.split()
>>> items.sort(explorer_cmp)
>>> for s in items:
...     print s,
1 2 10 20 a1 a2 a003 a10 b2 c100
>>> items.sort(key=natural_key, reverse=True)
>>> for s in items:
...     print s,
c100 b2 a10 a003 a2 a1 20 10 2 1
"""
import re

def natural_key(astr):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', astr)]

def natural_cmp(a, b):
    return cmp(natural_key(a), natural_key(b))

try: # use explorer's comparison function if available
    import ctypes
    explorer_cmp = ctypes.windll.shlwapi.StrCmpLogicalW
except (ImportError, AttributeError):
    # not on Windows or old python version
    explorer_cmp = natural_cmp        

if __name__ == '__main__':
    import doctest; doctest.testmod()

要支持Unicode字符串,.isdecimal()应该使用而不是.isdigit().

.isdigit()int()在某些语言环境中,Python 2上的字节串也可能失败(返回值不被接受),例如,Windows上的cp1252语言环境中的'\ xb2'('²').



2> Marius..:

JavaScript的

Array.prototype.alphanumSort = function(caseInsensitive) {
  for (var z = 0, t; t = this[z]; z++) {
    this[z] = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        this[z][++y] = "";
        n = m;
      }
      this[z][y] += j;
    }
  }

  this.sort(function(a, b) {
    for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
      if (caseInsensitive) {
        aa = aa.toLowerCase();
        bb = bb.toLowerCase();
      }
      if (aa !== bb) {
        var c = Number(aa), d = Number(bb);
        if (c == aa && d == bb) {
          return c - d;
        } else return (aa > bb) ? 1 : -1;
      }
    }
    return a.length - b.length;
  });

  for (var z = 0; z < this.length; z++)
    this[z] = this[z].join("");
}

资源



3> Rytis..:

对于MySQL,我个人使用Drupal模块中的代码,该模块可从hhttp://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x获得:/natsort.install.mysql

基本上,您执行发布的SQL脚本来创建函数,然后使用 ORDER BY natsort_canon(field_name, 'natural')

以下是该函数的自述文件:http://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x: /README.txt



4> Darius Bacon..:

下面是清理代码中的文章链接到的问题:

def sorted_nicely(strings): 
    "Sort strings the way humans are said to expect."
    return sorted(strings, key=natural_sort_key)

def natural_sort_key(key):
    import re
    return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]

但实际上我没有机会以这种方式排序.

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有