how to reverse a [][]string?

blov · 2018-01-26 14:30:02 · 571 次点击    
这是一个分享于 2018-01-26 14:30:02 的资源,其中的信息可能已经有所发展或是发生改变。
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:
for i := 0; i < len(x)/2; i++ {
    x[i], x[len(x)-i-1] = x[len(x)-i-1], x[i]
}

https://play.golang.org/p/Gd9d3R6ZhcR

Mteigers:

Feeling ok over there? Looks like you just threw up on your keyboard.

Kidding

Kraigius:

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
}

https://play.golang.org/p/qn0jqkIHI9U

decapolar:

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.

https://play.golang.org/p/Y-66zyGYULk

Kraigius:

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.


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

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