gpt4 book ai didi

arrays - 在 Swift 中,如何根据另一个数组对一个数组进行排序?

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

在 Swift 中,假设我有两个数组:

var array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
var array2: [Int] = [1, 0, 2, 0, 3]

现在,我想按升序对 array1 进行排序,并相应地重新索引 array2,以便得到

array1 = [1.2, 1.5, 2.4, 10.9, 20.4]
array2 = [1, 3, 0, 0, 2]

有没有一种简单的方法可以使用 Swift 函数或语法来做到这一点?

我知道我可以构建一个函数来执行此操作并且可以跟踪索引,但我很好奇是否有更优雅的解决方案。

最佳答案

let array1: [Double] = [1.2, 2.4, 20.0, 10.9, 1.5]
let array2: [Int] = [1, 0, 2, 0, 3]

// use zip to combine the two arrays and sort that based on the first
let combined = zip(array1, array2).sorted {$0.0 < $1.0}
print(combined) // "[(1.2, 1), (1.5, 3), (2.4, 0), (10.9, 0), (20.0, 2)]"

// use map to extract the individual arrays
let sorted1 = combined.map {$0.0}
let sorted2 = combined.map {$0.1}

print(sorted1) // "[1.2, 1.5, 2.4, 10.9, 20.0]"
print(sorted2) // "[1, 3, 0, 0, 2]"
<小时/>

对 2 个以上数组进行排序

如果您有 3 个或更多数组要一起排序,您可以对其中一个数组及其偏移量进行排序,使用map提取偏移,然后使用map对其他数组进行排序:

let english = ["three", "five", "four", "one", "two"]
let ints = [3, 5, 4, 1, 2]
let doubles = [3.0, 5.0, 4.0, 1.0, 2.0]
let roman = ["III", "V", "IV", "I", "II"]

// Sort english array in alphabetical order along with its offsets
// and then extract the offsets using map
let offsets = english.enumerated().sorted { $0.element < $1.element }.map { $0.offset }

// Use map on the array of ordered offsets to order the other arrays
let sorted_english = offsets.map { english[$0] }
let sorted_ints = offsets.map { ints[$0] }
let sorted_doubles = offsets.map { doubles[$0] }
let sorted_roman = offsets.map { roman[$0] }

print(sorted_english)
print(sorted_ints)
print(sorted_doubles)
print(sorted_roman)

输出:

["five", "four", "one", "three", "two"]
[5, 4, 1, 3, 2]
[5.0, 4.0, 1.0, 3.0, 2.0]
["V", "IV", "I", "III", "II"]

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

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