登录
首页 >  Golang >  Go问答

在 Golang 中是否有一种简洁的方式同时对多个键进行排序并将其插入到切片中?

来源:stackoverflow

时间:2024-03-07 13:12:25 131浏览 收藏

大家好,我们又见面了啊~本文《在 Golang 中是否有一种简洁的方式同时对多个键进行排序并将其插入到切片中?》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我在 python 中有一个函数,如下所示

def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people = sorted(people, key=lambda x: (-x[0], x[1]))
        ans = []
        for a in people:
            ans.insert(a[1], a)
        return ans

上述函数中有两件事。 1. 使用多键 x[0](降序)和 x[1](升序)对二维数组进行排序 2.通过循环向数组中插入一个元素

输入:[[7,0]、[4,4]、[7,1]、[5,0]、[6,1]、[5,2]]

我找不到在 golang 中实现此逻辑的简单或直接的方法。有人可以帮我用 go 方式翻译这段代码吗?


解决方案


package main

import (
    "container/list"
    "fmt"
    "sort"
)

type pair struct {
    x int
    y int
}

// print: prints the list
func print(l *list.List) {
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Printf("%v\n", e.Value)
    }
}

// do: does all the important operations
func do(queue []pair) *list.List {
    sort.Slice(queue, func(i, j int) bool {
        // If values are equal for first field then sort on
        // the basis of second field (ascending order)
        if queue[i].x == queue[j].x {
            return queue[i].y < queue[j].y
        }
        // Else sort on the basis of first field (decreasing order)
        return queue[i].x > queue[j].x
    })
    // Creates a list
    ans := list.New()
    for i := range queue {
        elem, ix, ixMark := &list.Element{}, 0, queue[i].y
        // Loops around to find the pos to fit in based on second field of element
        for elem = ans.Front(); elem != nil; elem = elem.Next() {
            if ix == ixMark {
                break
            }
            ix++
        }
        if elem == nil {
            // Add if list is empty
            ans.PushBack(queue[i])
        } else {
            // Add before the marked element
            ans.InsertBefore(queue[i], elem)
        }
    }
    return ans
}

func main() {
    elems := []pair{
        {7, 0},
        {4, 4},
        {7, 1},
        {5, 0},
        {6, 1},
        {5, 2},
    }
    queue := do(elems)
    print(queue)
    // Output:
    // {5 0}
    // {7 0}
    // {5 2}
    // {6 1}
    // {4 4}
    // {7 1}
}

代码已注释,以便您可以理解。因此基本上切片和列表的组合可以帮助您实现相同的目标。毫无疑问,在 go 中可能有更简单、更短的方法来做同样的事情。

我的实现非常简单。

本篇关于《在 Golang 中是否有一种简洁的方式同时对多个键进行排序并将其插入到切片中?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>