341

有没有什么类似于slice.contains(object)Go 中的方法而无需搜索切片中的每个元素?

4

18 回答 18

316

Mostafa 已经指出这样的方法写起来很简单,mkb 给了你一个使用 sort 包中的二分查找的提示。但是,如果您要进行大量此类包含检查,您也可以考虑使用地图。

value, ok := yourmap[key]通过使用习语来检查特定的映射键是否存在是微不足道的。由于您对该值不感兴趣,因此您还可以创建一个map[string]struct{}示例。在这里使用空struct{}的好处是它不需要任何额外的空间,并且 Go 的内部映射类型针对这种值进行了优化。因此,map[string] struct{}是围棋世界中集合的流行选择。

于 2012-05-07T17:14:15.653 回答
277

不,这种方法不存在,但写起来很简单:

func contains(s []int, e int) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

如果查找是代码的重要部分,您可以使用地图,但地图也有成本。

于 2012-05-07T16:56:58.983 回答
22

如果您的切片已排序或您愿意对其进行排序,则sort包提供了构建块。

input := []string{"bird", "apple", "ocean", "fork", "anchor"}
sort.Strings(input)

fmt.Println(contains(input, "apple")) // true
fmt.Println(contains(input, "grow"))  // false

...

func contains(s []string, searchterm string) bool {
    i := sort.SearchStrings(s, searchterm)
    return i < len(s) && s[i] == searchterm
}

SearchString承诺返回the index to insert x if x is not present (it could be len(a)),因此检查该字符串是否包含已排序的切片。

于 2019-09-20T10:46:14.913 回答
20

而不是使用slice,map可能是更好的解决方案。

简单的例子:

package main

import "fmt"


func contains(slice []string, item string) bool {
    set := make(map[string]struct{}, len(slice))
    for _, s := range slice {
        set[s] = struct{}{}
    }

    _, ok := set[item] 
    return ok
}

func main() {

    s := []string{"a", "b"}
    s1 := "a"
    fmt.Println(contains(s, s1))

}

http://play.golang.org/p/CEG6cu4JTf

于 2014-12-03T12:45:04.510 回答
17

如果切片已排序,则在包中实现了二进制sort搜索

于 2012-05-07T16:40:19.287 回答
8
func Contain(target interface{}, list interface{}) (bool, int) {
    if reflect.TypeOf(list).Kind() == reflect.Slice || reflect.TypeOf(list).Kind() == reflect.Array {
        listvalue := reflect.ValueOf(list)
        for i := 0; i < listvalue.Len(); i++ {
            if target == listvalue.Index(i).Interface() {
                return true, i
            }
        }
    }
    if reflect.TypeOf(target).Kind() == reflect.String && reflect.TypeOf(list).Kind() == reflect.String {
        return strings.Contains(list.(string), target.(string)), strings.Index(list.(string), target.(string))
    }
    return false, -1
}
于 2018-11-04T04:19:40.157 回答
5

在 Go 1.18+ 中,我们可以使用泛型。

func Contains[T comparable](s []T, e T) bool {
    for _, v := range s {
        if v == e {
            return true
        }
    }
    return false
}
于 2022-01-21T14:16:26.763 回答
4

您可以使用reflect包来迭代具体类型为切片的接口:

func HasElem(s interface{}, elem interface{}) bool {
    arrV := reflect.ValueOf(s)

    if arrV.Kind() == reflect.Slice {
        for i := 0; i < arrV.Len(); i++ {

            // XXX - panics if slice element points to an unexported struct field
            // see https://golang.org/pkg/reflect/#Value.Interface
            if arrV.Index(i).Interface() == elem {
                return true
            }
        }
    }

    return false
}

https://play.golang.org/p/jL5UD7yCNq

于 2016-09-01T04:00:19.833 回答
3

如果使用地图基于键查找项目不可行,则可以考虑使用goderive工具。Goderive 生成​​特定于类型的 contains 方法实现,使您的代码既可读又高效。

例子;

type Foo struct {
    Field1 string
    Field2 int
} 

func Test(m Foo) bool {
     var allItems []Foo
     return deriveContainsFoo(allItems, m)
}

要生成 derivedContainsFoo 方法:

  • 安装goderivego get -u github.com/awalterschulze/goderive
  • goderive ./...在您的工作区文件夹中运行

将为deriveContains 生成此方法:

func deriveContainsFoo(list []Foo, item Foo) bool {
    for _, v := range list {
        if v == item {
            return true
        }
    }
    return false
}

Goderive 支持一些其他有用的帮助方法来在 go 中应用函数式编程风格。

于 2018-04-08T09:43:34.430 回答
3

不确定这里是否需要泛型。你只需要一个你想要的行为的合同。如果您希望自己的对象在集合中表现自己,例如通过覆盖 Equals() 和 GetHashCode(),执行以下操作与在其他语言中必须执行的操作一样。

type Identifiable interface{
    GetIdentity() string
}

func IsIdentical(this Identifiable, that Identifiable) bool{
    return (&this == &that) || (this.GetIdentity() == that.GetIdentity())
}

func contains(s []Identifiable, e Identifiable) bool {
    for _, a := range s {
        if IsIdentical(a,e) {
            return true
        }
    }
    return false
}
于 2017-09-20T13:30:26.260 回答
2

我认为map[x]boolmap[x]struct{}.

为不存在的项目索引地图将返回false。因此_, ok := m[X],您可以直接说,而不是m[X]

这使得在表达式中嵌套包含测试变得容易。

于 2020-08-04T22:08:53.897 回答
1

我用这些答案的解决方案创建了一个非常简单的基准。

https://gist.github.com/NorbertFenk/7bed6760198800207e84f141c41d93c7

这不是一个真正的基准,因为最初,我没有插入太多元素,但可以随意分叉和更改它。

于 2020-01-29T16:15:41.913 回答
1

从 Go 1.18 开始,您可以使用该slices包 - 特别是通用Contains函数: https ://pkg.go.dev/golang.org/x/exp/slices#Contains 。

go get golang.org/x/exp/slices
import  "golang.org/x/exp/slices"
things := []string{"foo", "bar", "baz"}
slices.Contains(things, "foo") // true

请注意,由于它作为实验包在 stdlib 之外,因此它不受 Go 1 Compatibility Promise™ 的约束,并且在正式添加到 stdlib 之前可能会发生变化。

于 2022-02-18T23:54:59.980 回答
1

有几个包可以提供帮助,但这个似乎很有希望:

https://github.com/wesovlabs/koazee

var numbers = []int{1, 5, 4, 3, 2, 7, 1, 8, 2, 3}
contains, _ := stream.Contains(7)
fmt.Printf("stream.Contains(7): %v\n", contains)
于 2021-11-19T23:14:36.517 回答
0

围棋风格:

func Contains(n int, match func(i int) bool) bool {
    for i := 0; i < n; i++ {
        if match(i) {
            return true
        }
    }
    return false
}


s := []string{"a", "b", "c", "o"}
// test if s contains "o"
ok := Contains(len(s), func(i int) bool {
    return s[i] == "o"
})
于 2019-11-15T12:03:46.597 回答
0

如果你有一个byte切片,你可以使用bytes包:

package main
import "bytes"

func contains(b []byte, sub byte) bool {
   return bytes.Contains(b, []byte{sub})
}

func main() {
   b := contains([]byte{10, 11, 12, 13, 14}, 13)
   println(b)
}

suffixarray包装:

package main
import "index/suffixarray"

func contains(b []byte, sub byte) bool {
   return suffixarray.New(b).Lookup([]byte{sub}, 1) != nil
}

func main() {
   b := contains([]byte{10, 11, 12, 13, 14}, 13)
   println(b)
}

如果你有一个int切片,你可以使用intsets包:

package main
import "golang.org/x/tools/container/intsets"

func main() {
   var s intsets.Sparse
   for n := 10; n < 20; n++ {
      s.Insert(n)
   }
   b := s.Has(16)
   println(b)
}
于 2021-05-29T14:23:39.273 回答
-1

我使用反射包创建了以下包含函数。该函数可用于各种类型,如 int32 或 struct 等。

// Contains returns true if an element is present in a slice
func Contains(list interface{}, elem interface{}) bool {
    listV := reflect.ValueOf(list)

    if listV.Kind() == reflect.Slice {
        for i := 0; i < listV.Len(); i++ {
            item := listV.Index(i).Interface()

            target := reflect.ValueOf(elem).Convert(reflect.TypeOf(item)).Interface()
            if ok := reflect.DeepEqual(item, target); ok {
                return true
            }
        }
    }
    return false
}

contains 函数的用法如下

// slice of int32
containsInt32 := Contains([]int32{1, 2, 3, 4, 5}, 3)
fmt.Println("contains int32:", containsInt32)

// slice of float64
containsFloat64 := Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
fmt.Println("contains float64:", containsFloat64)


// slice of struct
type item struct {
    ID   string
    Name string
}
list := []item{
    item{
        ID:   "1",
        Name: "test1",
    },
    item{
        ID:   "2",
        Name: "test2",
    },
    item{
        ID:   "3",
        Name: "test3",
    },
}
target := item{
    ID:   "2",
    Name: "test2",
}
containsStruct := Contains(list, target)
fmt.Println("contains struct:", containsStruct)

// Output:
// contains int32: true
// contains float64: true
// contains struct: true

请在此处查看更多详细信息: https ://github.com/glassonion1/xgo/blob/main/contains.go

于 2021-02-25T01:25:39.380 回答
-4

它可能被认为有点“hacky”,但根据切片的大小和内容,您可以将切片连接在一起并进行字符串搜索。

例如,您有一个包含单个单词值的切片(例如“yes”、“no”、“maybe”)。这些结果被附加到一个切片中。如果您想检查此切片是否包含任何“可能”结果,您可以使用

exSlice := ["yes", "no", "yes", "maybe"]
if strings.Contains(strings.Join(exSlice, ","), "maybe") {
  fmt.Println("We have a maybe!")
}

这实际上有多合适取决于切片的大小和其成员的长度。大切片或长值可能存在性能或适用性问题,但对于有限大小和简单值的较小切片,它是实现所需结果的有效单线。

于 2020-02-07T05:14:31.037 回答