Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

algorithm - Iterating through 2 maps preserving order on same line output

I'm looking to iterate through 2 different maps, and have them output on a side by side basis like

foo --------- bar zoo--------- car

The problem stems from not being able to properly use 2 maps, although I dont have to use maps. the order of index doesnt matter but the key pair values must stay the same, so in this instance, zoo must be with car, but doesnt neccessarily have to be NEXT to foo bar,

for k, z := range teamA {
                    fmt.Fprintln(w, k+"  "+z)

                }
for k, z := range teamB {
                    fmt.Fprintln(w, k+"  "+z)

                }

But the error with this approach is it prints out all lines (each map has 5 values, so 10 lines total) in a block format like below, not side by side as i wish. How can I get it to print side by side? not like the block below

foo --- bar
zoo ------------ car
question from:https://stackoverflow.com/questions/65833004/iterating-through-2-maps-preserving-order-on-same-line-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Preload keys from TeamB to an array. Then use a simple counter inside the range loop of TeamA to retrieve a key from an array and a corresponding value from TeamB

keys := make([]string, len(teamA))
i := 0
for k := range teamA {
                    keys[i] = k
                    i++
                }
i = 0
for k, z := range teamB {
                    kA := keys[i]
                    vA := teamA[k]
                    fmt.Fprintf(w, "%v%v%v%v", k, z, kA, vA)
                    i++
                }

See https://play.golang.org/p/18Im2T3ZpCL
If the sizes of maps are different, don`t forget to account for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...