【问题标题】:Mixed lexicographic and numeric sorting混合字典和数字排序
【发布时间】:2010-12-16 14:47:13
【问题描述】:

我有一个列表,例如:

输入.txt

foo.bar.1
foo.bar.2
foo.bar.3.x.y.z
foo.bar.10
foo.bar.0
baz.10.qux
baz.3.qux

需要排序。我需要把它当作一个点分隔 字段,其中数字字段需要按数字排序。

所以我写了:

mixsort.py

​​>
#!/usr/bin/env python
import sys
seq = map(lambda l: map(lambda s: (s.isdigit() and [int(s)] or [s])[0], l),
          [ s.rstrip().split('.') for s in sys.stdin.readlines() ])
seq.sort()
sys.stdout.write( '\n'.join(['.'.join([str(i) for i in l]) for l in seq]) )

用法

$ mixsort.py < input.txt
baz.3.qux
baz.10.qux
foo.bar.0
foo.bar.1
foo.bar.2
foo.bar.3.x.y.z
foo.bar.10

但是我在这里重新发明轮子了吗?有没有共同点 *nix 实用程序可以满足我的需要吗?有没有切换到sort(1) 会帮助我。 (请注意,数字字段的位置是 未知)。有没有更好的方法来做同样的事情?

【问题讨论】:

    标签: sorting command-line text-processing unix


    【解决方案1】:

    coreutils 8.7 版

    使用版本排序:sort -V:

    输入:

    frayser@gentoo ~ $ cat /tmp/list.ran
    foo.bar.1
    foo.bar.2
    baz.10.qux
    baz.3.qux
    foo.bar.0
    foo.bar.3.x.y.z
    foo.bar.10
    

    排序:

    frayser@gentoo ~ $ LC_ALL=C sort -V /tmp/list.ran
    baz.3.qux
    baz.10.qux
    foo.bar.0
    foo.bar.1
    foo.bar.2
    foo.bar.3.x.y.z
    foo.bar.10
    
     
    

    我在 info pages 中找到了这个,正如手册页中所建议的那样:info coreutils "sort invocation"

    【讨论】:

    • 格栅建议。使用sort -Vsort --version-sort 是一个巧妙的技巧,它在我的问题和版本号中都利用了点分隔。这是这个问题的正确答案。不幸的是,我可用的sort(1) 版本不支持此选项。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多