How to iterate over multiple arrays?

blov · 2016-02-06 04:22:49 · 573 次点击    
这是一个分享于 2016-02-06 04:22:49 的资源,其中的信息可能已经有所发展或是发生改变。

So I have a problem I'm trying to solve, but I need to iterate over two separate arrays of type []string. Is there a way to accomplish this in Go? Kinda something like this:

for nope, yep := range firstArray, secondArray { fmt.Println(nope) fmt.Println(yep) }

Obviously that doesn't work, just trying to give you an idea of what I'm looking for.

EDIT:

Concatenating or comparing them isn't an option. I need to use the values in both arrays differently.


评论:

djherbis:

https://play.golang.org/p/qoGePCv9xm

muffinz0:

Thanks! Unfortunately that only works if both arrays are the same size, which won't always be the case. I updated your example to better describe my needs. https://play.golang.org/p/GNJ2tIRgnL

koalainthetree:

Can you take the length of the longest one and iterate over both of them that way?

muffinz0:

Actually, I just figured it out! https://play.golang.org/p/1Arw3M_KIn

fubo:

These are pretty different cases.

If you have arrays [1, 2, 3] and [4, 5], parallel iteration will yield two or three iterations:

  • x=1, y=4
  • x=2, y=5
  • ... followed by either skipping x=3 because there isn't a corresponding y value, or having an error, or assigning y to 0, or something else depending on how you code it.

Whereas nested iteration (one for loop inside another) will yield six iterations:

  • x=1, y=4
  • x=1, y=5
  • x=2, y=4
  • x=2, y=5
  • x=3, y=4
  • x=3, y=5

If you want to generate all possible pairings of elements from each array (a Cartesian product), you want nested iteration. If you want to step through both arrays in step with each other, pairing the elements from one array with corresponding elements of the other, you want parallel iteration.

djherbis:

https://play.golang.org/p/eASwJNh1xb

muffinz0:

Thank you for your help!

Fwippy:

You just need to use two normal loops, one inside the other.

https://play.golang.org/p/HY4aHJbjWl


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

573 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传