追加/添加到具有两个值的地图

我正在尝试在Go中创建一个映射,并根据从文件中读取的字符串切片中的正则表达式匹配为一个键分配两个值。


为此,我尝试使用两个for循环 - 一个用于分配第一个值,另一个用于分配下一个值(这应该使第一个值保持不变)。


到目前为止,我已经设法使正则表达式匹配工作,我可以创建字符串并将两个值中的任何一个放入映射中,或者我可以创建两个单独的映射,但这不是我打算做的。这是代码 Im 使用


package main


import (

    "fmt"

    "io/ioutil"

    "log"

    "regexp"

    "strings"

)


type handkey struct {

    game  string

    stake string

}

type handMap map[int]handkey


func main() {


    file, rah := ioutil.ReadFile("HH20201223.txt")

    if rah != nil {

        log.Fatal(rah)

    }

    str := string(file)


    slicedHands := strings.SplitAfter(str, "\n\n\n") //splits the string after two new lines, hands is a slice of strings


    mapHand := handMap{}


    for i := range slicedHands {

        matchHoldem, _ := regexp.MatchString(".+Hold'em", slicedHands[i]) //This line matches the regex

        if matchHoldem {                                                  //If statement does something if it's matched

            mapHand[i] = handkey{game: "No Limit Hold'em"} //This line put value of game to key id 'i'

        }


    }


    for i := range slicedHands {

        matchStake, _ := regexp.MatchString(".+(\\$0\\.05\\/\\$0\\.10)", slicedHands[i])

        if matchStake {

            mapHand[i] = handkey{stake: "10NL"}

        }

    }

    fmt.Println(mapHand)

我尝试过的事情...1)制作一个与两个表达式匹配的for循环(无法求解) 2)使用第一个值更新映射的第二个实例,以便将两个值都放在第二个循环中(无法求解)


我理解它再次重新创建地图,并且没有分配第一个值。


撒科打诨
浏览 95回答 1
1回答

MMMHUHU

试试这个:func main() {    file, rah := ioutil.ReadFile("HH20201223.txt")    if rah != nil {        log.Fatal(rah)    }    str := string(file)    slicedHands := strings.SplitAfter(str, "\n\n\n") //splits the string after two new lines, hands is a slice of strings    mapHand := handMap{}    for i := range slicedHands {        matchHoldem, _ := regexp.MatchString(".+Hold'em", slicedHands[i]) //This line matches the regex        matchStake, _ := regexp.MatchString(".+(\\$0\\.05\\/\\$0\\.10)", slicedHands[i])        h := handkey{}        if matchHoldem {            h.game = "No Limit Hold'em"        }        if matchStake {            h.stake = "10NL"        }        mapHand[i] = h    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go