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)


慕斯709654
浏览 521回答 3
3回答

肥皂起泡泡

我可能必须这样做:        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            }        }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go