douwei7976 2019-08-11 03:27
浏览 40
已采纳

按行值将[] []字符串分组(二维切片)

I'm working with a 2D slice of string in go and I want to group them by "A" column value but I couldn't figure it out.

I tried to use gota data frame but it also doesn't have group by like what is available in 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"},
    }

I want to have output like this.

[[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]]

  • 写回答

1条回答 默认 最新

  • dongsong8932 2019-08-11 03:57
    关注

    The following group() function utilizes a map to collect input string slices with the same [0] element, and then converts it back to 2D slice. This will do your work:

    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]]
    }
    

    Analysis of the above code is left as exercise. :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?