Slice chunking

agolangf · · 844 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello,</p> <p>I noticed a lack of support for splitting your slice into chunks of N.</p> <p>In python (I know, don&#39;t hurt me) the idiomatic way would be:</p> <blockquote> <blockquote> <blockquote> <blockquote> <p>x = [some list with multiple elements]</p> <p>chunked = [x[i:i+2] for i in range(0, len(x), 2)]</p> </blockquote> </blockquote> </blockquote> </blockquote> <p>Which would split x into N chunks of size 2, except for the last slice, which could be &lt;= 2. I provided list in the example but this also works with strings.</p> <p>I have a string that&#39;s always guaranteed to have its length be some multiple of 2 (with a min length of 4). I&#39;m not looking for the most similar pythonic way to do it. Instead, I&#39;m looking for the most golang-idiomatic way to split this into chunks of 2?</p> <p>Furthermore, these strings can get quite large. In terms of efficiency, I was looking at bytes.Buffer, but it seems (in terms of performance) the only difference it offers me over a string is mutability. However, since these strings won&#39;t be changed in anyway, it shouldn&#39;t really matter? Unless there&#39;s some performance hit reading a string vs a bytes.Buffer, but afaik, they both exist in memory as a contiguous block of memory, so reading speeds should be similar.</p> <hr/>**评论:**<br/><br/>TheMerovius: <pre><p>[edit] Apologies, I was thinking about splitting strings, here&#39;s for any <code>T</code>, basically :)[/edit]</p> <pre><code>var x []T var chunks [][]T for i := 0; i &lt; len(x); i += 2 { chunks = append(chunks, x[i:i+2]) } </code></pre> <p>The efficiency and everything is the same or better as with Python.</p></pre>nsd433: <pre><p>If you want a tiny bit more efficiency (especially of x tends to be long), pre-alloc `chunks`, since you know what length you&#39;ll need:</p> <p><code>var chunks = make([][]T, 0, (len(x)+1)/2)</code></p> <p>Depending on how clever the compiler is, it also might be slightly faster to have len(chunks) preset and assign</p> <p><code>chunks[i/2] = x[i:i+2]</code></p> <p>rather than append(). But you&#39;d have to measure.</p></pre>

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

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