【问题标题】:Appending/adding to a map with two values附加/添加到具有两个值的地图
【发布时间】:2021-01-22 18:58:55
【问题描述】:

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

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

【问题讨论】:

    标签: go maps key-value


    【解决方案1】:

    试试这个:

    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 和一般编程的新手。这使得代码更简洁,也更容易阅读和扩展。再次感谢,一切顺利。
    • 请将此标记为答案 - 这将使其他人更容易找到此解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2018-12-04
    • 2014-06-07
    相关资源
    最近更新 更多