dongzouche9108 2017-09-17 06:03
浏览 14
已采纳

按具有相同值的字符串顺序对结构进行排序

I'm trying to sort a collection of structs by the order of another strings characters with the same values.

Here's an example:

package main

import (
    "fmt"
    "sort"
    "strings"
)

type Container struct {
    Initial  string
}

func main() {
    s := "dfah"
    c := []Container{}

    for _, r := range "fadh" {
        c = append(c, Container{Initial: string(r)})
    }

    sort.Slice(c, func(i, j int) bool {
        str := strings.Compare(c[i].Initial, s)

        if str == -1 {
            return true
        } else {
            return false
        }
    })

    fmt.Printf("Result: %s
", c) // returns 'dafh'
    fmt.Printf("Desired result: %s
", s) // returns 'dfah'
}

The desired result would be the sorted collection of Container structs, with the same order of the 'dfah' string.

https://play.golang.org/p/eDW5-xpCzv

They will always have the same characters/number of characters, just unsorted. I'm not sure what the correct way to accomplish this is. Any ideas? Thanks!

  • 写回答

1条回答 默认 最新

  • dongqi7631 2017-09-17 06:16
    关注

    In your slice-sorting function, you're comparing c[i].Initial to s. That's simply wrong. Instead, you want to find whether c[i].Initial appears in s before or after c[j].Initial.

    Here's some example code, or see it running on the playground:

    package main
    
    import (
        "fmt"
        "sort"
        "strings"
    )
    
    type Container struct {
        Initial string
    }
    
    func main() {
        s := "dfah"
        c := []Container{}
    
        for _, r := range "fadh" {
            c = append(c, Container{Initial: string(r)})
        }
    
        sort.Slice(c, func(i, j int) bool {
            return strings.Index(s, c[i].Initial) <= strings.Index(s, c[j].Initial)
        })
    
        fmt.Printf("Result: %s
    ", c)         // returns [{d} {f} {a} {h}]
        fmt.Printf("Desired result: %s
    ", s) // returns 'dfah'
    }
    

    Note in practice, this is inefficient, since it involves scanning s lots of times. If this were real code, I'd be building a map from characters of s to their index so that the strings.Index calls could be replaced by map lookups.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解