x := [][]string{
[]string{"1.1.1.1", "1111"}, // old one
[]string{"2.2.2.2", "2222"}, // new one
}
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.
评论:
peterbourgon:
Mteigers:for i := 0; i < len(x)/2; i++ { x[i], x[len(x)-i-1] = x[len(x)-i-1], x[i] }
Kraigius:Feeling ok over there? Looks like you just threw up on your keyboard.
Kidding
decapolar: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.
for _, element := range x { defer fmt.Printf("%#+v\n", element) }
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:
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 }
Kraigius:Perfect solution. But I want to know why we use the sort.Reverse() 2 times?
edit //
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.
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.
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.
