golang中遍历汇总
直接上例子:
例子1:
package main import( "fmt" ) func main(){ a := map[string]string{ "alice":"11", "bob":"29", "zhangsan":"29", "wang":"35", } tmpRs := map[string][]string{} for k1, v1 := range a { tmpRs[v1] = append(tmpRs[v1], k1) } fmt.Printf("tmpRs.........=%v",tmpRs) }
根据value,把Value相同的放在一起,结果放在一个大map里.
执行结果如下:
> tmpRs.........=map[11:[alice] 29:[bob zhangsan] 35:[wang]]
例子2:
// json.go package main import ( "encoding/json" "fmt" "strconv" ) type FakeUserInfo struct { Push_Type string `json:"push_type"` // 渠道 Third_Token string `json:"third_token"` // token User_id string `json:"user_id"` // 用户ID } // return: map[int]map[string][]string :{0: {"Users":["2","3","4"],"Tokens":["234","234"]}} func main() { var m FakeUserInfo var tmpRs = map[int]map[string][]string{} str := `{"push_type": "0","user_id": "fake_22222","third_token": "22222"}` json.Unmarshal([]byte(str), &m) fmt.Println(m) fmt.Println("pushType......",m.Push_Type) fmt.Println("thirdToken......",m.Third_Token) fmt.Println("userId......",m.User_id) if len(m.Push_Type) == 0 { return } i, _ := strconv.Atoi(m.Push_Type) if tmpRs[i] == nil { tmpRs[i] = map[string][]string{} } if tmpRs[i]["Users"] == nil { tmpRs[i]["Users"] = []string{} } if m.Third_Token == "" || m.User_id == "" { return } tmpRs[i]["Users"] = append(tmpRs[i]["Users"], m.User_id) if tmpRs[i]["Tokens"] == nil { tmpRs[i]["Tokens"] = []string{} } tmpRs[i]["Tokens"] = append(tmpRs[i]["Tokens"], m.Third_Token) fmt.Printf("tmpRs.........=%v",tmpRs) }
把结果放在一个复合map中.
执行结果如下:
> {0 22222 fake_22222}
> pushType...... 0
> thirdToken...... 22222
> userId...... fake_22222
> tmpRs.........=map[0:map[Users:[fake_22222] Tokens:[22222]]]