Go 使用两个值追加/添加到映射
我试图在Go中创建一个映射,并根据从文件读取的字符串片段中的正则表达式匹配,将两个值分配给一个键 为此,我尝试使用两个for循环-一个用于指定第一个值,第二个用于指定下一个值(第一个值应保持不变) 到目前为止,我已经设法让正则表达式匹配工作,我可以创建字符串并将两个值中的一个放入映射,或者我可以创建两个单独的映射,但这不是我想要做的。这是我使用的代码Go 使用两个值追加/添加到映射,go,maps,key-value,Go,Maps,Key Value,我试图在Go中创建一个映射,并根据从文件读取的字符串片段中的正则表达式匹配,将两个值分配给一个键 为此,我尝试使用两个for循环-一个用于指定第一个值,第二个用于指定下一个值(第一个值应保持不变) 到目前为止,我已经设法让正则表达式匹配工作,我可以创建字符串并将两个值中的一个放入映射,或者我可以创建两个单独的映射,但这不是我想要做的。这是我使用的代码 package main import ( "fmt" "io/ioutil"
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)为两个表达式都匹配的循环制作一个(无法解决)
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和编程都是新手。这使得代码更清晰,更易于阅读和扩展。再次感谢您,祝您一切顺利。请将此标记为答案-这将使其他人更容易找到此解决方案