在Swift中查找数组数组中的值(类似于Excel中的VLOOKUP函数) [英] Finding a value in an array of arrays (similar to VLOOKUP function in Excel) in Swift
问题描述
我对Swift 3和一般的编程语言还是陌生的。我在数组和变量收入中有以下数组:
I am quite new to Swift 3 and to programming languages in general. I have the following arrays inside an array and a variable income:
let testArray: [[Double]] = [
[0,0],
[1000,20.5],
[3000,21],
[4000,22.5],
]
var income: Double = 3500
我要执行的操作类似于Excel中的VLOOKUP函数:我想在数组的第一列(即0、1000、3000、4000)中找到一个等于或立即小于我的变量的数字。在这种情况下,当收入= 3500时,程序应返回3000。我尝试使用filter(),但是我不知道如何处理数组中的数组。感谢所有帮助。
What I want to do is something similar to the VLOOKUP function in Excel: I want to find in the first column of the arrays (i.e. 0, 1000, 3000, 4000) a number which is equal or immediately smaller than my variable. In this case, as income = 3500, the program should return 3000. I tried using filter() but I don't know how to work with the arrays inside the array. Any help appreciated.
推荐答案
您可以按照以下步骤进行操作。
You can proceed as follows.
获取数组的第一列:
let firstColumn = testArray.map { $0[0] }
print(firstColumn) // [0.0, 1000.0, 3000.0, 4000.0]
限制为小于或等于给定的
金额:
Restrict to those elements which are less than or equal to the given amount:
let filtered = firstColumn.filter { $0 <= income }
print(filtered) // [0.0, 1000.0, 3000.0]
获取最大的元素过滤后的数组。如果元素是按升序排序的
,则可以使用 last
代替 max()
:
Get the maximal element of the filtered array. If the elements are
sorted in increasing order then you can use last
instead of max()
:
let result = filtered.max()!
// Or: let result = filtered.last!
print(result) // 3000.0
将它们放在一起:
let result = testArray.map { $0[0] }.filter { $0 <= income }.max()!
print(result) // 3000.0
可能的优化是合并 map
和 filter
到
flatMap
:
A possible optimization is to combine map
and filter
into
flatMap
:
let result = testArray.flatMap { $0[0] <= income ? $0[0] : nil }.max()!
print(result) // 3000.0
此代码假定至少有一个匹配项元素,否则
否则 last!
或 max()!
会崩溃。如果不能保证:
This code assumes that there is at least one matching element,
otherwise last!
or max()!
would crash. If that is not guaranteed:
if let result = testArray.flatMap( { $0[0] <= income ? $0[0] : nil }).max() {
print(result) // 3000.0
} else {
print("no result")
}
或提供默认值(在此示例中为 0.0
):
Or provide a default value (0.0
in this example):
let result = testArray.flatMap( { $0[0] <= income ? $0[0] : nil }).max() ?? 0.0
print(result) // 3000.0
这篇关于在Swift中查找数组数组中的值(类似于Excel中的VLOOKUP函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!