猿问

在 Go 中实现 Ruby 风格的笛卡尔积

我想得到a, b, c,的笛卡尔积d:


a = ['a1']

b = ['b1', 'b2']

c = ['c1', 'c2', 'c3']

d = ['d1']

这是Ruby中的代码:


e = [b, c, d]

print a.product(*e)

输出是:


[

  ["a1", "b1", "c1", "d1"],

  ["a1", "b1", "c2", "d1"],

  ["a1", "b1", "c3", "d1"],

  ["a1", "b2", "c1", "d1"],

  ["a1", "b2", "c2", "d1"],

  ["a1", "b2", "c3", "d1"]

]

是否有类似的包或功能可以在 Golang 中做产品?这只是简化版,实际上输入的数据就像 [['a1'], ['b1','b2'], ['c1','c2','c3],['d1'], ['e1',...],...]。


一只萌萌小番薯
浏览 192回答 1
1回答

四季花海

如果您需要一组在编译时未知的嵌套索引循环,您可以使用这样的代码。package mainimport "fmt"// NextIndex sets ix to the lexicographically next value,// such that for each i>0, 0 <= ix[i] < lens(i).func NextIndex(ix []int, lens func(i int) int) {&nbsp; &nbsp; for j := len(ix) - 1; j >= 0; j-- {&nbsp; &nbsp; &nbsp; &nbsp; ix[j]++&nbsp; &nbsp; &nbsp; &nbsp; if j == 0 || ix[j] < lens(j) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ix[j] = 0&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; e := [][]string{&nbsp; &nbsp; &nbsp; &nbsp; {"a1"},&nbsp; &nbsp; &nbsp; &nbsp; {"b1", "b2"},&nbsp; &nbsp; &nbsp; &nbsp; {"c1", "c2", "c3"},&nbsp; &nbsp; &nbsp; &nbsp; {"d1"},&nbsp; &nbsp; }&nbsp; &nbsp; lens := func(i int) int { return len(e[i]) }&nbsp; &nbsp; for ix := make([]int, len(e)); ix[0] < lens(0); NextIndex(ix, lens) {&nbsp; &nbsp; &nbsp; &nbsp; var r []string&nbsp; &nbsp; &nbsp; &nbsp; for j, k := range ix {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; r = append(r, e[j][k])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(r)&nbsp; &nbsp; }}输出是:[a1 b1 c1 d1][a1 b1 c2 d1][a1 b1 c3 d1][a1 b2 c1 d1][a1 b2 c2 d1][a1 b2 c3 d1]
随时随地看视频慕课网APP

相关分类

Go
我要回答