golang中的多维数组

Odi*_*sky 5 go

来自使用数组(PHP)的语言并且只有 3 天的 golang 经验,我如何使用 map(或切片,或组合)翻译多维数组分配

我在 PHP 中有这个代码: $set 是文档向量的集合(字符串 => 频率)。

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

$postinglist = array();  

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

      if(!isset($postinglist[$term][$id])) {
          $postinglist[$term][$id] = $value;
      }
}
Run Code Online (Sandbox Code Playgroud)

所以它看起来像:

array ( 
   'the' => array ( 
      1 => 5, 
      2 => 10 
      ), 
   'and' => array ( 
      1 => 6, 
      3 => 7
      )
    )
Run Code Online (Sandbox Code Playgroud)

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

$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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道在 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
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

postinglist[str] = make(map[int]float64)
Run Code Online (Sandbox Code Playgroud)

pet*_*rSO 4

如果地图是 ,则制作地图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)
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场: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]]
Run Code Online (Sandbox Code Playgroud)