登录
首页 >  Golang >  Go问答

在映射中增加包含两个值的附加项

来源:stackoverflow

时间:2024-02-19 12:51:25 137浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《在映射中增加包含两个值的附加项》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

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

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

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

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)使用第一个值更新地图的第二个实例,以便两个值都放在第二个循环中(无法解决)

我理解它再次重新创建地图,并且没有分配第一个值。 感谢您的帮助!


解决方案


试试这个:

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
    }
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在映射中增加包含两个值的附加项》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>