以字母顺序获取映射中的键的简便方法

huangapple go评论81阅读模式
英文:

Easy way to get the keys in a map in alphabetical order

问题

在Go语言中,按字母顺序获取映射中的键的最简单方法是什么?这是我能做到的最简短的方法:

package main

import "container/vector"
import "fmt"
import "sort"

func main() {
    m := map[string]string {"b":"15", "z":"123123", "x":"sdf", "a":"12"}
    var keys vector.StringVector;
    for k,_ := range ( m ) {
        keys.Push(k)
    }
    sort.Sort( &keys )
    fmt.Printf("%v\n", keys)
}

请注意,这是一个Go语言代码示例,用于按字母顺序获取映射中的键,并打印排序后的结果。

英文:

In Go, what's the easiest way to get the keys in a map sorted alphabetically? This is the shortest way I can do it:

package main

import "container/vector"
import "fmt"
import "sort"

func main() {
    m := map[string]string {"b":"15", "z":"123123", "x":"sdf", "a":"12"}
    var keys vector.StringVector;
    for k,_ := range ( m ) {
            keys.Push(k)
    }
    sort.Sort( &keys )
    fmt.Printf("%v\n", keys)
}

答案1

得分: 57

你正在使用StringVector对字符串数组进行排序。为了最小化开销,你可以对字符串数组进行排序。

package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
	mk := make([]string, len(m))
	i := 0
	for k, _ := range m {
		mk[i] = k
		i++
	}
	sort.Strings(mk)
	fmt.Println(mk)
}

输出:

[a b x z]
英文:

You are sorting an array of strings using StringVector. To minimize overhead, you could sort an array of strings.

package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
	mk := make([]string, len(m))
	i := 0
	for k, _ := range m {
		mk[i] = k
		i++
	}
	sort.Strings(mk)
	fmt.Println(mk)
}

Output:

[a b x z]

答案2

得分: 17

那将是最优雅的方法:

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
    keys := make([]string, 0, len(m))
    for key := range m {
        keys = append(keys, key)
    }
    sort.Strings(keys)
    fmt.Println(keys)
}
英文:

That would be most elegant method:

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]string{"b": "15", "z": "123123", "x": "sdf", "a": "12"}
    keys := make([]string, 0, len(m))
    for key := range m {
        keys = append(keys, key)
    }
    sort.Strings(keys)
    fmt.Println(keys)
}

huangapple
  • 本文由 发表于 2010年1月11日 04:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/2038508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定