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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)