gpt4 book ai didi

arrays - 对数组 [(int, int)] 排序,以便在 scala 中列出

转载 作者:行者123 更新时间:2023-12-02 04:28:36 24 4
gpt4 key购买 nike

我目前正在使用 Scala 开发 Spark 框架。
我有一个数组 C: Array[(int, int)] 我想根据 map A:Map[int,int] 的顺序对其进行排序。代码如下:

line 1:import scala.util.Sorting
line 2: object Test {
line 3: def main(args: Array[String]){
line 4: val A = Map(5 -> 41, 1 -> 43, 2 -> 41, 3 -> 59,4 -> 51 )
line 5: val B= A.toList.sortBy(x => x._2)
line 6: B.foreach(println)
line 7: val C=Array((1,15),(2,9),(3,6),(4,3),(5,4))
line 8: Sorting.quickSort(C)(Ordering[(Int)].on(k => (A.get(k._1).get)))
line 9: for(j <- 0 to C.length-1){
line 10: println(C(j))
line 11: }
line 12: }
line 13: }

当我根据值部分(第 5 行)对 A 进行排序并打印时,我得到如下输出(第 6 行):
(5,41)
(2,41)
(1,43)
(4,51)
(3,59)

但是当我根据 A 的关键部分(第 8 行)对 C 进行排序时,我得到以下输出(第 9-11 行)
(2,9)
(5,4)
(1,15)
(4,3)
(3,6)

由于 (5,41) 和 (2,41) 具有相同的值,并且在 B 中 (5,41) 出现在 (2,41) 之前。但是根据A的关键部分对C进行排序后,为什么2出现在5之前。为什么B和C的结果都不统一?

请建议我更改代码以在 B 和 C 中获得统一的结果。我希望 C 为: (5,4) (2,9) (1,15) (4,3) (3,6) .

最佳答案

Map按设计是无序的,因此按 value 排序单独可能会导致不确定的顺序。如果您的业务逻辑允许更改排序标准,请考虑通过 value + key 排序使其保持一致在 Map 上和 Array :

import scala.util.Sorting

val A = Map(5 -> 41, 1 -> 43, 2 -> 41, 3 -> 59, 4 -> 51 )
val B = A.toList.sortBy(x => (x._2, x._1))

B
// res1: List[(Int, Int)] = List((2,41), (5,41), (1,43), (4,51), (3,59))

val C = Array((1,15),(2,9),(3,6),(4,3),(5,4))

Sorting.quickSort(C)(Ordering[(Int, Int)].on( k => (A.get(k._1).get, k._1) ))

C
// res23: Array[(Int, Int)] = Array((2,9), (5,4), (1,15), (4,3), (3,6))

附带说明,为避免因找不到 key 而崩溃,请考虑使用 gerOrElse具有默认值(例如 Int.MaxValue 等):
Sorting.quickSort(C)(Ordering[(Int, Int)].on( k => (A.getOrElse(k._1, Int.MaxValue), k._1) ))

关于arrays - 对数组 [(int, int)] 排序,以便在 scala 中列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303848/

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