为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
撒科打诨 2022-08-01 17:27:11
我正在尝试在Go中创建一个映射,并根据从文件中读取的字符串切片中的正则表达式匹配为一个键分配两个值。为此,我尝试使用两个for循环 - 一个用于分配第一个值,另一个用于分配下一个值(这应该使第一个值保持不变)。到目前为止,我已经设法使正则表达式匹配工作,我可以创建字符串并将两个值中的任何一个放入映射中,或者我可以创建两个单独的映射,但这不是我打算做的。这是代码 Im 使用package mainimport (    "fmt"    "io/ioutil"    "log"    "regexp"    "strings")type handkey struct {    game  string    stake string}type handMap map[int]handkeyfunc 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)使用第一个值更新映射的第二个实例,以便将两个值都放在第二个循环中(无法求解)我理解它再次重新创建地图,并且没有分配第一个值。
查看完整描述

1 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

试试这个:


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

    }

}


查看完整回答
反对 回复 2022-08-01
  • 1 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号