Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File 在Go中按数字顺序对文件进行排序_File_Sorting_For Loop_Go - Fatal编程技术网

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

File 在Go中按数字顺序对文件进行排序,file,sorting,for-loop,go,File,Sorting,For Loop,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()) } 我要找的订单是1,2,3。。。9,10,11,12

我正在读一个目录,我注意到如果我有按数字(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())
    }
我要找的订单是1,2,3。。。9,10,11,12,13

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

谢谢。

您能否根据您的要求实施界面和订单?给定返回的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())
}
键入ByNumericalFilename[]os.FileInfo
func(nf ByNumericalFilename)Len()int{return Len(nf)}
func(nf ByNumericalFilename)交换(i,j int){nf[i],nf[j]=nf[j],nf[i]}
func(nf ByNumericalFilename)减去(i,j int)bool{
//使用路径名
路径:=nf[i].Name()
路径B:=nf[j]。名称()
//通过解析字符串并切分,获取每个文件名的整数值
//分机
a、 err1:=strconv.ParseInt(路径[0:strings.LastIndex(路径,“.”),10,64)
b、 err2:=strconv.ParseInt(路径b[0:strings.LastIndex(路径b,“.”),10,64)
//如果数字不是按字母顺序排列的
如果err1!=nil | | err2!=nil{
返回路径A<路径B
}
//哪个整数更小?
返回a

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

我在发布问题后不久就有了这个想法;最后我写的不一样,但非常感谢你的帮助。我接受了你的答案,因为如果我使用它,它会给我想要的。@BenCampbell,你在上次编辑时添加了一个语法错误。@DaveC谢谢!现场编写代码总是有风险的。