<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'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 <= 2. I provided list in the example but this also works with strings.</p>
<p>I have a string that's always guaranteed to have its length be some multiple of 2 (with a min length of 4). I'm not looking for the most similar pythonic way to do it. Instead, I'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't be changed in anyway, it shouldn't really matter? Unless there'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's for any <code>T</code>, basically :)[/edit]</p>
<pre><code>var x []T
var chunks [][]T
for i := 0; i < 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'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'd have to measure.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传