How to iterate over multiple arrays?

blov · · 507 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So I have a problem I&#39;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:</p> <p><code>for nope, yep := range firstArray, secondArray { fmt.Println(nope) fmt.Println(yep) }</code></p> <p>Obviously that doesn&#39;t work, just trying to give you an idea of what I&#39;m looking for.</p> <p>EDIT:</p> <p>Concatenating or comparing them isn&#39;t an option. I need to use the values in both arrays differently.</p> <hr/>**评论:**<br/><br/>djherbis: <pre><p><a href="https://play.golang.org/p/qoGePCv9xm">https://play.golang.org/p/qoGePCv9xm</a></p></pre>muffinz0: <pre><p>Thanks! Unfortunately that only works if both arrays are the same size, which won&#39;t always be the case. I updated your example to better describe my needs. <a href="https://play.golang.org/p/GNJ2tIRgnL" rel="nofollow">https://play.golang.org/p/GNJ2tIRgnL</a></p></pre>koalainthetree: <pre><p>Can you take the length of the longest one and iterate over both of them that way?</p></pre>muffinz0: <pre><p>Actually, I just figured it out! <a href="https://play.golang.org/p/1Arw3M_KIn" rel="nofollow">https://play.golang.org/p/1Arw3M_KIn</a></p></pre>fubo: <pre><p>These are pretty different cases.</p> <p>If you have arrays [1, 2, 3] and [4, 5], <em>parallel iteration</em> will yield two or three iterations:</p> <ul> <li>x=1, y=4</li> <li>x=2, y=5</li> <li>... followed by either skipping x=3 because there isn&#39;t a corresponding y value, or having an error, or assigning y to 0, or something else depending on how you code it.</li> </ul> <p>Whereas <em>nested iteration</em> (one for loop inside another) will yield six iterations:</p> <ul> <li>x=1, y=4</li> <li>x=1, y=5</li> <li>x=2, y=4</li> <li>x=2, y=5</li> <li>x=3, y=4</li> <li>x=3, y=5</li> </ul> <p>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 <em>both</em> arrays <em>in step</em> with each other, pairing the elements from one array with <em>corresponding</em> elements of the other, you want parallel iteration.</p></pre>djherbis: <pre><p><a href="https://play.golang.org/p/eASwJNh1xb">https://play.golang.org/p/eASwJNh1xb</a></p></pre>muffinz0: <pre><p>Thank you for your help!</p></pre>Fwippy: <pre><p>You just need to use two normal loops, one inside the other.</p> <p><a href="https://play.golang.org/p/HY4aHJbjWl">https://play.golang.org/p/HY4aHJbjWl</a></p></pre>

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

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