1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

golang[][]stringでのtranspose(転置)

Last updated at Posted at 2020-04-16

####goalngで[[][][][][]]のような二次元配列の順番をtranspose(縦横変換)する。
・csvを読み込んだ際に変換したくなったので、その部分を抜粋。

main.go
package main

import "fmt"

func transpose(slice [][]string) [][]string {
	xl := len(slice[0])
	yl := len(slice)
	result := make([][]string, xl)
	for i := range result {
		result[i] = make([]string, yl)
	}
	for i := 0; i < xl; i++ {
		for j := 0; j < yl; j++ {
			result[i][j] = slice[j][i]
		}
	}
	return result
}

func main() {
	sample := [][]string{
		[]string{"a1", "a2", "a3", "a4", "a5"},
		[]string{"b1", "b2", "b3", "b4", "b5"},
		[]string{"c1", "c2", "c3", "c4", "c5"},
	}
	fmt.Println(sample)
	ar := transpose(sample)
	fmt.Println(ar)
}

参考
https://gist.github.com/tanaikech/5cb41424ff8be0fdf19e78d375b6adb8

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?