在Go中按数字顺序对文件进行排序

q3d*_*q3d 2 sorting for-loop file go

我正在读一个目录,有了这个,我注意到如果我有按数字排序的文件(1,2,3,4 ......),那么它似乎使用了一些字母顺序.

假设我有13个文件(名为1.md,2.md,3.md ......),排序看起来像:1,10,11,12,13,2,3,4 ...; 我用来生成此订单的当前代码是:

files, _ := ioutil.ReadDir(my_dir)
    for _, f := range files {
        fmt.Println(f.Name())
    }
Run Code Online (Sandbox Code Playgroud)

我要找的订单是1,2,3,... 9,10,11,12,13.

如何对这些文件进行严格的数字排序?请记住,每个文件都名为N.md,其中N保证是大于或等于0的整数.

谢谢.

Ben*_*ell 9

您能否根据您的要求实施排序界面和订单?给定返回的os.FileInfo元素片段,您可以使用数字顺序而不是字典顺序排列它们.

type ByNumericalFilename []os.FileInfo

func (nf ByNumericalFilename) Len() int      { return len(nf) }
func (nf ByNumericalFilename) Swap(i, j int) { nf[i], nf[j] = nf[j], nf[i] }
func (nf ByNumericalFilename) Less(i, j int) bool {

    // Use path names
    pathA := nf[i].Name()
    pathB := nf[j].Name()

    // Grab integer value of each filename by parsing the string and slicing off
    // the extension
    a, err1 := strconv.ParseInt(pathA[0:strings.LastIndex(pathA, ".")], 10, 64)
    b, err2 := strconv.ParseInt(pathB[0:strings.LastIndex(pathB, ".")], 10, 64)

    // If any were not numbers sort lexographically
    if err1 != nil || err2 != nil {
        return pathA < pathB
    }

    // Which integer is smaller?
    return a < b
}

files, _ := ioutil.ReadDir(".")

sort.Sort(ByNumericalFilename(files))

for _, f := range files {
    fmt.Println(f.Name())
}
Run Code Online (Sandbox Code Playgroud)

我知道它不是很简洁,但却是一个有效的答案.