<pre><code>x := [][]string{
[]string{"1.1.1.1", "1111"}, // old one
[]string{"2.2.2.2", "2222"}, // 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 < 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'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("%#+v\n", 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 "fmt"
import "sort"
type MyType [][]string
func main() {
x := MyType{
[]string{"1.1.1.1", "1111"},
[]string{"2.2.2.2", "2222"},
[]string{"3.3.3.3", "3333"},
}
sort.Sort(sort.Reverse(x))
fmt.Printf("%#+v\n", 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 < 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't have to. I'm just an idiot who coded at midnight.
I'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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传