GoLang:检查 Slice 1 中的项是否存在于 Slice 2 中。如果存在,则移除 Slice 2。

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

GoLang: Check if item from Slice 1 contains in Slice 2. If it does, remove Slice 2

问题

我有一个字符串数组:slice1 [][]string。
我使用for循环获取我想要的值:

for _, i := range slice1 { //[string1 string2]
	fmt.Println("server: ", i[1]) //只想要数组中的第二个字符串。
}

现在我有另一个字符串数组:slice2 [][]string
我也使用for循环获取它的值:

for _, value := range output { //
	fmt.Println(value) //输出:[ 200K, 2, "a", 22, aa-d-2, sd , MatchingString, a ]
}

我想遍历slice1,并检查string2是否与slice2中的"MatchingString"匹配。如果匹配,就不打印该值数组。

我再次创建了一个for循环来实现这个目的,但它不起作用:

for _, value := range slice2 {
	for _, i := range slice1 {
		if strings.Contains(value[0], i[1]) {
			//跳过
		} else {
			fmt.Println(value)
		}
	}
}

这是一个示例代码:https://play.golang.org/p/KMVzB2jlbG
有什么办法可以实现这个?谢谢!

英文:

I have a string array: slice1 [][]string.
I get the values I want using a for loop:

for _, i := range slice1 { //[string1 string2]
	fmt.Println("server: ", i[1]) //only want the second string in the array.
}

Now I have another string array: slice2 [][]string
I get its values using a for loop as well:

for _, value := range output { //
	fmt.Println(value) //Prints: [ 200K, 2, "a", 22, aa-d-2, sd , MatchingString, a ]
}

I want to iterate through slice1 and check if the string2 matches "MatchingString" in Slice2. If it does, don't print the value array.

I created a for loop again to do this but its not working:

for _, value := range slice2 {
	for _, i := range slice1 {
		if strings.Contains(value[0], i[1]) {
			//skip over
		} else {
			fmt.Println(value)
		}
	}
}

Here's a sample code: https://play.golang.org/p/KMVzB2jlbG
Any idea on how to do this? Thanks!

答案1

得分: 1

如果我正确理解你的问题,你想要打印出所有满足以下条件的slice2的子切片:其中的字符串都不是slice1中某个切片的第二个元素。如果是这样,你可以通过以下代码实现:

Slice2Loop:
	for _, value := range slice2 {
		for _, slice2string := range value {
			for _, i := range slice1 {
				if slice2string == i[1] {
					continue Slice2Loop
				}
			}
		}
		fmt.Println(value)
	}

这段代码使用了三层嵌套的循环。首先,外层的循环遍历slice2中的每个子切片。然后,内层的两个循环分别遍历当前子切片中的每个字符串和slice1中的每个切片。如果发现当前字符串是某个切片的第二个元素,就通过continue Slice2Loop语句跳过当前子切片的处理。如果没有找到匹配的情况,就打印出当前子切片。

英文:

If I'm reading your question correctly, you are trying to print all those subslices of slice2 that have the property that none of the strings within are the second element of a slice in slice1. If so, you can obtain that through

Slice2Loop:
	for _, value := range slice2 {
		for _, slice2string := range value {
			for _, i := range slice1 {
				if slice2string == i[1] {
					continue Slice2Loop
				}
			}
		}
		fmt.Println(value)
	}

huangapple
  • 本文由 发表于 2017年2月18日 23:58:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/42317372.html
匿名

发表评论

匿名网友

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

确定