登录
首页 >  Golang >  Go问答

golang中的多维数组

来源:stackoverflow

时间:2024-04-09 13:42:39 306浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《golang中的多维数组》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

来自使用数组(php)的语言,并且只有 3 天的 golang 经验,如何使用映射(或切片或组合)转换多维数组赋值

我的 php 代码如下: $set 是文档向量的集合(字符串 => 频率)。

我通常可以创建这样的发布统计信息:

$postinglist = array();  

foreach ($set as $id=>$doc) {
      foreach ($doc as $term => $value) {

      if(!isset($postinglist[$term][$id])) {
          $postinglist[$term][$id] = $value;
      }
}

所以它看起来像:

array ( 
   'the' => array ( 
      1 => 5, 
      2 => 10 
      ), 
   'and' => array ( 
      1 => 6, 
      3 => 7
      )
    )

构建我的语料库后(只是所有文档中所有术语的数组), 然后我将为每个术语建立发布列表:

$terms = $this->getallterms();

foreach($terms as $term) {
    $entry = new entrystatistics();

    foreach($postinglist[$term] as $id => $value) {
       $post = new postingstatistics;
       $post->settf($value);
       $entry->setpostinglist($id, $post);
    }
}

我想知道在 golang 中是否有一种巧妙的方法可以做到这一点,就像我尝试过的那样:

postinglist := make(map[string]map[int]float64)
for id, doc := range indexmanager.getdocuments() {
  for str, tf := range doc {
      _, ok_pl := postinglist[str][id]
      if !ok_pl {
          postinglist[str] = make(map[int]float64)
          postinglist[str][id] = tf
      }
   }
}

当然它不起作用,因为每次我这样做它总是初始化地图:

postinglist[str] = make(map[int]float64)

解决方案


如果地图是nil,则制作地图。例如,

package main

import (
    "fmt"
    "math"
)

func main() {
    tests := []struct {
        s string
        i int
        f float64
    }{
        {"s", 42, math.pi},
        {"s", 100, math.e},
        {"s", 100, 1000.0},
        {"x", 1, 2.0},
    }

    var m map[string]map[int]float64
    fmt.println(m)
    for _, t := range tests {
        if m == nil {
            m = make(map[string]map[int]float64)
        }
        if m[t.s] == nil {
            m[t.s] = make(map[int]float64)
        }
        m[t.s][t.i] += t.f
        fmt.println(m)
    }
}

演示:https://play.golang.org/p/IBZxGgAi6eL

输出:

map[]
map[s:map[42:3.141592653589793]]
map[s:map[42:3.141592653589793 100:2.718281828459045]]
map[s:map[42:3.141592653589793 100:1002.718281828459]]
map[s:map[42:3.141592653589793 100:1002.718281828459] x:map[1:2]]

我可能必须这样做:

v_pl, ok_pl := postinglist[str]
        if !ok_pl {
            _, ok_pl2 := v_pl[id]
            if !ok_pl2 {
                postinglist[str] = map[int]float64{id: tf}
            }
        } else {
            _, ok_pl2 := v_pl[id]
            if !ok_pl2 {
                postinglist[str][id] = tf
            }
        }

今天关于《golang中的多维数组》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>