将麻木数字化功能转化为 go

数字化函数返回输入数组中每个值所属的条柱的索引。


下面的代码来自蟒蛇 -


x = np.array([0.8, 6.9, 3.5, 1.9])

bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])

inds = np.digitize(x, bins)

print(inds)

array([1, 4, 3, 2])


HUX布斯
浏览 72回答 2
2回答

不负相思意

这是这样做的:package mainimport (   "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

智慧大石

package mainimport (&nbsp; &nbsp; "errors"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sort")type arr []float64func (a arr) Less(i, j int) bool {&nbsp; &nbsp; return a[i] < a[j]}func (in arr) digitize(bins arr) ([]int, error) {&nbsp; &nbsp; if !sort.SliceIsSorted(bins, bins.Less) {&nbsp; &nbsp; &nbsp; &nbsp; return nil, errors.New("bins array is not sorted")&nbsp; &nbsp; }&nbsp; &nbsp; indices := make([]int, len(in))&nbsp; &nbsp; for i, x := range in {&nbsp; &nbsp; &nbsp; &nbsp; indices[i] = sort.SearchFloat64s(bins, x)&nbsp; &nbsp; }&nbsp; &nbsp; return indices, nil}func main() {&nbsp; &nbsp; var (&nbsp; &nbsp; &nbsp; &nbsp; x&nbsp; &nbsp; = arr{0.8, 6.9, 3.5, 1.9}&nbsp; &nbsp; &nbsp; &nbsp; bins = arr{0.0, 1.0, 2.5, 4.0, 10.0}&nbsp; &nbsp; )&nbsp; &nbsp; indices, err := x.digitize(bins)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(indices)}楼盘: https://golang.org/pkg/sort#SearchFloat64s搜索浮动64s在浮点数的排序切片中搜索x64,并返回搜索指定的索引。返回值是如果 x 不存在时插入 x 的索引(它可能是 len(a))。切片必须按升序排序。
打开App,查看更多内容
随时随地看视频慕课网APP