2 回答
TA贡献1777条经验 获得超10个赞
这是这样做的:
package main
import (
"fmt"
"sort"
)
func digitize(x, bins []float64) []int {
inds := make([]int, len(x))
for k, v := range x {
inds[k] = sort.SearchFloat64s(bins, v)
}
return inds
}
func main() {
x := []float64{0.8, 6.9, 3.5, 1.9}
bins := []float64{0, 1, 2.5, 4, 10}
inds := digitize(x, bins)
fmt.Println(inds) // [1 4 3 2]
}
https://golang.org/pkg/sort#SearchFloat64s
TA贡献1946条经验 获得超3个赞
package main
import (
"errors"
"fmt"
"sort"
)
type arr []float64
func (a arr) Less(i, j int) bool {
return a[i] < a[j]
}
func (in arr) digitize(bins arr) ([]int, error) {
if !sort.SliceIsSorted(bins, bins.Less) {
return nil, errors.New("bins array is not sorted")
}
indices := make([]int, len(in))
for i, x := range in {
indices[i] = sort.SearchFloat64s(bins, x)
}
return indices, nil
}
func main() {
var (
x = arr{0.8, 6.9, 3.5, 1.9}
bins = arr{0.0, 1.0, 2.5, 4.0, 10.0}
)
indices, err := x.digitize(bins)
if err != nil {
panic(err)
}
fmt.Println(indices)
}
楼盘: https://golang.org/pkg/sort#SearchFloat64s
搜索浮动64s在浮点数的排序切片中搜索x64,并返回搜索指定的索引。返回值是如果 x 不存在时插入 x 的索引(它可能是 len(a))。切片必须按升序排序。
- 2 回答
- 0 关注
- 91 浏览
添加回答
举报