在Swift中,如何基于另一个数组对一个数组进行排序?

编程入门 行业动态 更新时间:2024-10-12 05:44:25
本文介绍了在Swift中,如何基于另一个数组对一个数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Swift中,说我有两个数组:

In Swift, say I have two arrays:

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

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

Now, I want to sort array1 in ascending order and reindex array2 accordingly so that I get

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

是否有使用Swift函数或语法执行此操作的简单方法?

Is there a simple way to do this using Swift functions or syntax?

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

I know I can build a function to do it and can keep track of indices, but I'm curious if there is a more elegant solution.

推荐答案

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]"

将两个以上的数组排序在一起

如果要对3个或更多数组进行排序,则可以sort其中一个数组及其offset,使用map提取offsets,然后使用map进行排序其他数组:

If you have 3 or more arrays to sort together, you can sort one of the arrays along with its offsets, use map to extract the offsets, and then use map to order the other arrays:

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"]

更多推荐

在Swift中,如何基于另一个数组对一个数组进行排序?

本文发布于:2023-11-29 04:06:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!