how to reverse a [][]string?

blov · · 395 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>x := [][]string{ []string{&#34;1.1.1.1&#34;, &#34;1111&#34;}, // old one []string{&#34;2.2.2.2&#34;, &#34;2222&#34;}, // new one } </code></pre> <p>i am just scraping some proxies and because that Regexp#FindAllStringSubmatch scans the page from bottom to top, i have to reverse order this custom [][]string to get the fresh ones on the top.</p> <hr/>**评论:**<br/><br/>peterbourgon: <pre><pre><code>for i := 0; i &lt; len(x)/2; i++ { x[i], x[len(x)-i-1] = x[len(x)-i-1], x[i] } </code></pre> <p><a href="https://play.golang.org/p/Gd9d3R6ZhcR" rel="nofollow">https://play.golang.org/p/Gd9d3R6ZhcR</a></p></pre>Mteigers: <pre><p>Feeling ok over there? Looks like you just threw up on your keyboard. </p> <p>Kidding </p></pre>Kraigius: <pre><p>I like defer, really easy to read. Although if you actually want it to be reversed in the variable you&#39;re better off iterating over to swap the values. This is just a fun example.</p> <pre><code>for _, element := range x { defer fmt.Printf(&#34;%#+v\n&#34;, element) } </code></pre> <p>You can also overly complicate things by using your own type and implementing the Sort interface. I would only consider it if you end up doing lots of reversing all around. It will be easier to refactor later on:</p> <pre><code>package main import &#34;fmt&#34; import &#34;sort&#34; type MyType [][]string func main() { x := MyType{ []string{&#34;1.1.1.1&#34;, &#34;1111&#34;}, []string{&#34;2.2.2.2&#34;, &#34;2222&#34;}, []string{&#34;3.3.3.3&#34;, &#34;3333&#34;}, } sort.Sort(sort.Reverse(x)) fmt.Printf(&#34;%#+v\n&#34;, x) } func (p MyType) Len() int { return len(p) } func (p MyType) Swap(i, j int) { p[i], p[j] = p[j], p[i] } func (p MyType) Less(i, j int) bool { return i &lt; j } </code></pre> <p><a href="https://play.golang.org/p/qn0jqkIHI9U" rel="nofollow">https://play.golang.org/p/qn0jqkIHI9U</a></p></pre>decapolar: <pre><p>Perfect solution. But I want to know why we use the sort.Reverse() 2 times?</p> <p>edit //</p> <p>BTW, I have just come by a function Sort#Slice and Sort#SliceStable which makes the reverse job simpler. I guess this is much more convenient.</p> <p><a href="https://play.golang.org/p/Y-66zyGYULk" rel="nofollow">https://play.golang.org/p/Y-66zyGYULk</a></p></pre>Kraigius: <pre><p>Ah well, you don&#39;t have to. I&#39;m just an idiot who coded at midnight. I&#39;ve corrected the Less function and adjusted the call.</p> <p>As you found out, things are a lot simpler if you use a StringSlice, a Float64Slice, or an IntSlice since the package already implements the Sort interface for them.</p></pre>

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

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