按行值对 [][]string(2D 切片)进行分组

我正在 go 中处理字符串的 2D 切片,我想按“A”列值对它们进行分组,但我无法弄清楚。


我尝试使用 gota 数据框,但它也没有像 pandas 中可用的分组依据。


    input := [][]string{

        []string{"b", "3", "2.9", "5.3"},

        []string{"a", "4", "5.1", "9.1"},

        []string{"b", "4", "6.0", "5.3"},

        []string{"c", "3", "6.0", "5.5"},

        []string{"a", "2", "7.1", "9.2"},

    }

我想要这样的输出。


[[b 3 2.9 5.3 4 6.0 5.3] [a 4 5.1 9.1 2 7.1 9.2] [c 3 6.0 5.5]]


梦里花落0921
浏览 96回答 1
1回答

素胚勾勒不出你

以下group()函数利用映射来收集具有相同 [0] 元素的输入字符串切片,然后将其转换回 2D 切片。这将完成你的工作:func group(input [][]string) (output [][]string) {&nbsp; &nbsp; tmp := map[string][]string{}&nbsp; &nbsp; for _, slice := range input {&nbsp; &nbsp; &nbsp; &nbsp; if len(slice) <= 1 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; tmp[slice[0]] = append(tmp[slice[0]], slice[1:]...)&nbsp; &nbsp; }&nbsp; &nbsp; for k := range tmp {&nbsp; &nbsp; &nbsp; &nbsp; v := append([]string{k}, tmp[k]...)&nbsp; &nbsp; &nbsp; &nbsp; output = append(output, v)&nbsp; &nbsp; }&nbsp; &nbsp; return}func main() {&nbsp; &nbsp; input := [][]string{&nbsp; &nbsp; &nbsp; &nbsp; []string{"b", "3", "2.9", "5.3"},&nbsp; &nbsp; &nbsp; &nbsp; []string{"a", "4", "5.1", "9.1"},&nbsp; &nbsp; &nbsp; &nbsp; []string{"b", "4", "6.0", "5.3"},&nbsp; &nbsp; &nbsp; &nbsp; []string{"c", "3", "6.0", "5.5"},&nbsp; &nbsp; &nbsp; &nbsp; []string{"a", "2", "7.1", "9.2"},&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(group(input)) // [[a 4 5.1 9.1 2 7.1 9.2] [c 3 6.0 5.5] [b 3 2.9 5.3 4 6.0 5.3]]}对上面代码的分析留作练习。:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go