來自使用數組(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)
3 回答

肥皂起泡泡
TA貢獻1829條經驗 獲得超6個贊
我可能必須這樣做:
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
}
}
- 3 回答
- 0 關注
- 552 瀏覽
添加回答
舉報
0/150
提交
取消