如何找出切片中的元素位置?

时间:2011-11-29 07:57:11

标签: position go slice

如何确定切片中存在的元素的位置?

我需要以下内容:

type intSlice []int

func (slice intSlice) pos(value int) int {
    for p, v := range slice {
        if (v == value) {
            return p
        }
    }
    return -1
}

8 个答案:

答案 0 :(得分:60)

抱歉,没有通用的库函数来执行此操作。 Go没有直接的方法来编写可以在任何切片上运行的函数。

您的功能有效,但如果您使用range编写它会更好一些。

如果碰巧有字节切片,则有bytes.IndexByte

答案 1 :(得分:46)

你可以用惯用的方式创建泛型函数:

func SliceIndex(limit int, predicate func(i int) bool) int {
    for i := 0; i < limit; i++ {
        if predicate(i) {
            return i
        }
    }
    return -1
}

用法:

xs := []int{2, 4, 6, 8}
ys := []string{"C", "B", "K", "A"}
fmt.Println(
    SliceIndex(len(xs), func(i int) bool { return xs[i] == 5 }),
    SliceIndex(len(xs), func(i int) bool { return xs[i] == 6 }),
    SliceIndex(len(ys), func(i int) bool { return ys[i] == "Z" }),
    SliceIndex(len(ys), func(i int) bool { return ys[i] == "A" }))

答案 2 :(得分:7)

你可以写一个函数;

Money myMoneyField = (Money)EntityObject.GetAttributeValue<Money>(Amount);

decimal actualAmount;

if (myMoneyField != null)
{
    actualAmount = myMoneyField.Value;
}
else 
{ 
    actualAmount = 0; 
}

Entity.Attributes.Add("budget_amount", new Money(actualAmount));

如果匹配元素,则返回字符/字符串的索引。如果未找到,则返回-1。

答案 3 :(得分:5)

没有库功能。你必须自己编码。

答案 4 :(得分:1)

另一种选择是使用排序包对切片进行排序,然后搜索您要查找的内容:

package main

import (
    "sort"
    "log"
    )

var ints = [...]int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}

func main() {
        data := ints
        a := sort.IntSlice(data[0:])
        sort.Sort(a)
        pos := sort.SearchInts(a, -784)
        log.Println("Sorted: ", a)
        log.Println("Found at index ", pos)
}

打印

2009/11/10 23:00:00 Sorted:  [-5467984 -784 0 0 42 59 74 238 905 959 7586 7586 9845]
2009/11/10 23:00:00 Found at index  1

这适用于基本类型,如果您需要处理其他事情,则可以始终为自己的类型实现排序接口。见http://golang.org/pkg/sort

取决于你在做什么。

答案 5 :(得分:1)

func index(slice []string, item string) int {
    for i, _ := range slice {
        if slice[i] == item {
            return i
        }
    }
    return -1
}

答案 6 :(得分:0)

几个月前,我遇到了同样的问题,并通过两种方式解决了问题:

第一种方法:

func Find(slice interface{}, f func(value interface{}) bool) int {
    s := reflect.ValueOf(slice)
    if s.Kind() == reflect.Slice {
        for index := 0; index < s.Len(); index++ {
            if f(s.Index(index).Interface()) {
                return index
            }
        }
    }
    return -1
}

使用示例:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 12,
    }) 
    
    idx := Find(destinationList, func(value interface{}) bool {
        return value.(UserInfo).UserId == userId
    })
    
    if idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

计算成本较低的第二种方法:

func Search(length int, f func(index int) bool) int {
    for index := 0; index < length; index++ {
        if f(index) {
            return index
        }
    }
    return -1
}

使用示例:

type UserInfo struct {
    UserId          int
}

func main() {
    var (
        destinationList []UserInfo
        userId      int = 123
    )
    
    destinationList = append(destinationList, UserInfo { 
        UserId          : 23,
    }) 
    destinationList = append(destinationList, UserInfo { 
        UserId          : 123,
    }) 
    
    idx := Search(len(destinationList), func(index int) bool {
        return destinationList[index].UserId == userId
    })
    
    if  idx < 0 {
        fmt.Println("not found")
    } else {
        fmt.Println(idx)    
    }
}

答案 7 :(得分:0)

如果您的切片已排序,另一种选择是使用 SearchInts(a []int, x int) int,它返回元素索引(如果找到)或元素应插入的索引(如果元素不存在)。< /p>

s := []int{3,2,1}
sort.Ints(s)
fmt.Println(sort.SearchInts(s, 1)) // 0
fmt.Println(sort.SearchInts(s, 4)) // 3

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