1 回答
TA贡献1827条经验 获得超9个赞
以下group()函数利用映射来收集具有相同 [0] 元素的输入字符串切片,然后将其转换回 2D 切片。这将完成你的工作:
func group(input [][]string) (output [][]string) {
tmp := map[string][]string{}
for _, slice := range input {
if len(slice) <= 1 {
continue
}
tmp[slice[0]] = append(tmp[slice[0]], slice[1:]...)
}
for k := range tmp {
v := append([]string{k}, tmp[k]...)
output = append(output, v)
}
return
}
func main() {
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"},
}
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]]
}
对上面代码的分析留作练习。:)
- 1 回答
- 0 关注
- 95 浏览
添加回答
举报