遍历映射的所有键

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

Iterating over all the keys of a map

问题

有没有办法获取Go语言地图中所有键的列表?元素的数量可以通过len()函数获得,但如果我有一个地图,像这样:

m := map[string]string{ "key1":"val1", "key2":"val2" };

我如何遍历所有的键?

英文:

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:

m := map[string]string{ "key1":"val1", "key2":"val2" };

How do I iterate over all the keys?

答案1

得分: 734

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

或者

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go语言for语句的规范指定第一个值是键,第二个变量是值,但不一定要存在。

英文:

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

答案2

得分: 21

这是一种获取地图键的简单方法。

// 返回给定地图的键
func Keys(m map[string]interface{}) (keys []string) {
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

// 使用 `Keys` 函数
func main() {
    m := map[string]interface{}{
        "foo": 1,
        "bar": true,
        "baz": "baz",
    }
    fmt.Println(Keys(m)) // [foo bar baz]
}
英文:

Here's some easy way to get slice of the map-keys.

// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
	for k := range m {
		keys = append(keys, k)
	}
	return keys
}

// use `Keys` func
func main() {
	m := map[string]interface{}{
		"foo": 1,
		"bar": true,
		"baz": "baz",
	}
	fmt.Println(Keys(m)) // [foo bar baz]
}

答案3

得分: 19

有没有办法获取Go语言中map的所有键的列表?

ks := reflect.ValueOf(m).MapKeys()

如何遍历所有的键?

使用接受的答案:

for _, k := range m { ... }
英文:

> Is there a way to get a list of all the keys in a Go language map?

ks := reflect.ValueOf(m).MapKeys()

> how do I iterate over all the keys?

Use the accepted answer:

for _, k := range m { ... }

答案4

得分: 6

一个类型不可知的解决方案:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := yourMap.MapIndex(key).Interface()
    fmt.Println("键:", key, "值:", value)
}
英文:

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := yourMap.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

答案5

得分: 4

使用泛型:

func Keys[K comparable, V any](m map[K]V) []K {
    keys := make([]K, 0, len(m))

    for k := range m {
        keys = append(keys, k)
    }

    return keys
}
英文:

Using Generics:

func Keys[K comparable, V any](m map[K]V) []K {
    keys := make([]K, 0, len(m))

    for k := range m {
        keys = append(keys, k)
    }

    return keys
}

答案6

得分: 0

对于map[string]string的排序键

package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]string{"key1": "val1", "key2": "val2"}
	sortStringMap(m)
}

// sortStringMap按键排序打印[string]string
func sortStringMap(m map[string]string) {
	var keys []string
	for key := range m {
		keys = append(keys, key)
	}
	sort.Strings(keys) // 对键进行排序
	for _, key := range keys {
		fmt.Printf("%s\t:%s\n", key, m[key])
	}
}

输出:

key1    :val1
key2    :val2

英文:

For sorted keys of map[string]string.

package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]string{"key1": "val1", "key2": "val2"}
	sortStringMap(m)
}

// sortStringMap prints the [string]string as keys sorted
func sortStringMap(m map[string]string) {
	var keys []string
	for key := range m {
		keys = append(keys, key)
	}
	sort.Strings(keys)  // sort the keys
	for _, key := range keys {
		fmt.Printf("%s\t:%s\n", key, m[key])
	}
}

output:

key1    :val1
key2    :val2

huangapple
  • 本文由 发表于 2009年12月4日 01:15:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/1841443.html
匿名

发表评论

匿名网友

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

确定