gpt4 book ai didi

go - 如何按两个值对 map 进行排序?

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:30 28 4
gpt4 key购买 nike

我正在尝试按 map 的两个值对 map 进行排序。首先是时间戳,然后是随机数。换句话说,我需要能够首先迭代并打印具有最小时间戳的 map ,然后是 nonce 值。像这样:

    "tx1": Transaction{Value:10, Nonce:1, Timestamp:1563543005},
"tx2": Transaction{Value:20, Nonce:2, Timestamp:1563543005},
"tx6": Transaction{Value:60, Nonce:2, Timestamp:1563543005},
"tx5": Transaction{Value:50, Nonce:4, Timestamp:1563543005},
"tx7": Transaction{Value:70, Nonce:1, Timestamp:1563543006},
"tx3": Transaction{Value:30, Nonce:3, Timestamp:1563543006},
"tx4": Transaction{Value:40, Nonce:4, Timestamp:1563543006},

这是我的代码:

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

package main

import (
"fmt"
"sort"
)

type Transaction struct {
Value uint64 `json:"value"`
Nonce uint64 `json:"nonce"`
Timestamp int64 `json:"timestamp"`
}

func main() {
// To create a map as input
memPool := map[string]Transaction {
"tx1": Transaction{Value:10, Nonce:1, Timestamp:1563543005},
"tx2": Transaction{Value:20, Nonce:2, Timestamp:1563543005},
"tx3": Transaction{Value:30, Nonce:3, Timestamp:1563543006},
"tx4": Transaction{Value:40, Nonce:4, Timestamp:1563543006},
"tx5": Transaction{Value:50, Nonce:4, Timestamp:1563543005},
"tx6": Transaction{Value:60, Nonce:2, Timestamp:1563543005},
"tx7": Transaction{Value:70, Nonce:1, Timestamp:1563543006},
}


keys := make([]string, 0, len(memPool))
for key := range memPool {
keys = append(keys, key)
}

sort.Slice(keys, func(i, j int) bool { return memPool[keys[i]].Timestamp > memPool[keys[j]].Timestamp })


for _, v := range keys {
fmt.Println(v)
}
fmt.Println("")

keys2 := make([]string, 0, len(memPool))
for key2 := range memPool {
keys2 = append(keys2, key2)
}

sort.Slice(keys2, func(i, j int) bool { return memPool[keys2[i]].Nonce > memPool[keys2[j]].Nonce })

for _, v := range keys2 {
fmt.Println(v)
}

}

当前输出:

tx7
tx3
tx4
tx1
tx2
tx5
tx6

tx4
tx5
tx3
tx6
tx2
tx7
tx1

期望的输出:

tx1
tx2
tx6
tx5
tx7
tx3
tx4

最佳答案

当您似乎想要排序一次时,您正在对两个不同的时间进行排序。因此,排序一次,使用您想要用于对值排序的所有逻辑,一次。

sort.Slice(keys, func(i, j int) bool {
if memPool[keys[i]].Timestamp == memPool[keys[j]].Timestamp {
if memPool[keys[i]].Nonce == memPool[keys[j]].Nonce {
return memPool[keys[i]].Value < memPool[keys[j]].Value
}
return memPool[keys[i]].Nonce < memPool[keys[j]].Nonce
}
return memPool[keys[i]].Timestamp < memPool[keys[j]].Timestamp
})

工作示例:https://play.golang.org/p/GERCSchEtOf

关于go - 如何按两个值对 map 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57115423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com