sort.Slice help

blov · · 550 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><a href="https://play.golang.org/p/wpcFO8SjDq">https://play.golang.org/p/wpcFO8SjDq</a></p> <p>I&#39;m trying to sort a slice, but relevant sort field has some sentinel data (in this case -1) that I want to sort to the end of the list, instead of it&#39;s natural order. Can anyone look at the playground example above and get the sort to work, but with values of -1 at the end of the list?</p> <hr/>**评论:**<br/><br/>_nefario_: <pre><p>if you need -1 to be at the end, the Less func should have a special rule for that value to override the comparison</p> <p>example: <a href="https://play.golang.org/p/5UNxnIKDHw" rel="nofollow">https://play.golang.org/p/5UNxnIKDHw</a></p></pre>caseynashvegas: <pre><p>Thanks, that&#39;s golden, I was only thinking about checking the i side, not both. </p></pre>element131: <pre><p><a href="https://play.golang.org/p/ThqpRp3IGT" rel="nofollow">https://play.golang.org/p/ThqpRp3IGT</a></p> <pre><code>sort.Slice(data, func(i, j int) bool { return data[i].Value &lt; data[j].Value || (data[j].Value == -1) }); </code></pre></pre>caseynashvegas: <pre><p>I think this is the best answer, are there any use cases it misses?</p></pre>nsd433: <pre><p>What about putting the -1 at the end to start with and calling sort.Sort(slice[0:len(slice)-1])</p> <p>That won&#39;t move the -1 since it doesn&#39;t know about it.</p></pre>caseynashvegas: <pre><p>I&#39;m not one to complain, but why did someone down vote this question? Seems shitty to down vote a legitimate question with an example on the playground. And at least to me, the answer was non obvious. If you&#39;re going to down vote you should at least comment as to why in my opinion.</p></pre>very-little-gravitas: <pre><p>You can also use sort.SliceStable to combine several sort criteria</p> <p><a href="https://play.golang.org/p/qeJhbexl33" rel="nofollow">https://play.golang.org/p/qeJhbexl33</a></p></pre>

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

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