生成特定顺序的单词组合的 Golang 代码是什么?

huangapple go评论80阅读模式
英文:

Golang code to generate specific sequential word combinations?

问题

我正在尝试用Go语言编写代码,但是还在学习阶段,遇到了一些困难。我想要一个能够完成以下功能的代码:

生成两个单词序列的连续组合列表,例如:

第一组单词:A, B, C, ..... J

第二组单词:K, L, M, ..... T

所需列表:

Test_A_K,
Test_A_L,
Test_A_M,

等等

Test_B_K,
Test_B_L,
Test_B_M,

等等

对于所有"Test_第一组单词_第二组单词"的组合

我尝试了一些来自该网站的其他代码,但不确定是否正确 - 如果有任何指导意见,将不胜感激

谢谢!

英文:

I'm trying to write a code in GoLang and am struggling, as am still learning a lot. I would like a code that would do the following:

Generate list of sequential combinations of two words, for example

Word Group One: A, B, C, ..... J

Word Group Two: K, L, M, ..... T

List needed:

Test_A_K,
Test_A_L,
Test_A_M,

etc

Test_B_K,
Test_B_L,
Test_B_M,

etc

for all combinations of "Test_Word Group One_Word Group Two"

Ive tried to implement some other codes from this site, but am not sure if i am doing the correct thing - any pointers would be most appreciated

Thanks!!

答案1

得分: 1

你可能需要一个嵌套的for循环。例如,

package main

import "fmt"

func pairs(words1, words2 []string) []string {
    pairs := make([]string, 0, len(words1)*len(words2))
    for _, word1 := range words1 {
        for _, word2 := range words2 {
            pairs = append(pairs, word1+"_"+word2)
        }
    }
    return pairs
}

func main() {
    w1 := []string{"a", "b", "c", "j"}
    fmt.Printf("%q\n", w1)
    w2 := []string{"k", "l", "m", "t"}
    fmt.Printf("%q\n", w2)
    p := pairs(w1, w2)
    fmt.Printf("%q\n", p)
}

输出:

["a" "b" "c" "j"]
["k" "l" "m" "t"]
["a_k" "a_l" "a_m" "a_t" "b_k" "b_l" "b_m" "b_t" "c_k" "c_l" "c_m" "c_t" "j_k" "j_l" "j_m" "j_t"]
英文:

You probably need a nested for loop. For example,

package main

import "fmt"

func pairs(words1, words2 []string) []string {
	pairs := make([]string, 0, len(words1)*len(words2))
	for _, word1 := range words1 {
		for _, word2 := range words2 {
			pairs = append(pairs, word1+"_"+word2)
		}
	}
	return pairs
}

func main() {
	w1 := []string{"a", "b", "c", "j"}
	fmt.Printf("%q\n", w1)
	w2 := []string{"k", "l", "m", "t"}
	fmt.Printf("%q\n", w2)
	p := pairs(w1, w2)
	fmt.Printf("%q\n", p)
}

Output:

["a" "b" "c" "j"]
["k" "l" "m" "t"]
["a_k" "a_l" "a_m" "a_t" "b_k" "b_l" "b_m" "b_t" "c_k" "c_l" "c_m" "c_t" "j_k" "j_l" "j_m" "j_t"]

huangapple
  • 本文由 发表于 2015年11月12日 00:23:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/33655033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定