gpt4 book ai didi

arrays - 如何根据行中的值对 Swift 中的二维数组列进行排序?

转载 作者:行者123 更新时间:2023-11-30 10:43:36 26 4
gpt4 key购买 nike

如何根据其中一行中的值对二维数组进行排序?

let array = [["X", "Y",   1,  2,  3,  4,  5],
["V", "W", "A","B","C","D","E"]
]

let sorted = [["X", "Y", 5, 4, 3, 2, 1],
["V", "W", "E","D","C","B","A"]
]

swift Array.sort({e1, e2 in e1 < e2})传入行元素,而不是列元素。

更糟糕的是,该行中的前两列不得排序。

请记住,第 2 行必须根据第 1 行的顺序重新排列。因此,假设我们按第 0 行排序并忽略第 1 2 列

[["X", "Y",   1,  2,  3,  4,  5],
["V", "W", "E","B","A","D","F"]]

应该变成

[["X", "Y",   5,  4,  3,  2,  1],
["V", "W", "F","D","A","B","E"]]

最佳答案

首先映射数组元素并从子数组中拆分前 2 个元素以跳过排序。现在使用开关模式匹配对剩余元素进行排序。然后将排序后的数组与前 2 个元素连接起来。

let array = [["X", "Y",   1,  2,  3,  4,  5],
["V", "W", "A","B","C","D","E"]]

let sorted = array.map { $0[..<2] + $0[2...].sorted(by: {
switch ($0,$1) {
case (let a as Int, let b as Int): return a > b
case (let a as String, let b as String): return a > b
case (let a as Date, let b as Date): return a > b
case (_, _): return false
}
})}.map { Array($0) }
print(sorted)

[["X", "Y", 5, 4, 3, 2, 1], ["V", "W", "E", "D", "C", "B", "A"]]

关于arrays - 如何根据行中的值对 Swift 中的二维数组列进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292310/

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