[英]Finding a value in an array of arrays (similar to VLOOKUP function in Excel) in Swift
I am quite new to Swift 3 and to programming languages in general. 我对Swift 3和一般的编程语言还是陌生的。 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
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 (ie 0, 1000, 3000, 4000) a number which is equal or immediately smaller than my variable. 我想做的事情类似于Excel中的VLOOKUP函数:我想在数组的第一列(即0、1000、3000、4000)中找到一个等于或立即小于我的变量的数字。 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. 在这种情况下,当收入= 3500时,程序应返回3000。我尝试使用filter(),但是我不知道如何处理数组中的数组。 Any help appreciated. 任何帮助表示赞赏。
You can proceed as follows. 您可以按如下进行操作。
Get the first column of the array: 获取数组的第一列:
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]
Get the maximal element of the filtered array. 获取过滤后的数组的最大元素。 If the elements are sorted in increasing order then you can use last
instead of max()
: 如果元素按升序排序,则可以使用last
而不是max()
:
let result = filtered.max()!
// Or: let result = filtered.last!
print(result) // 3000.0
Putting it all together: 放在一起:
let result = testArray.map { $0[0] }.filter { $0 <= income }.max()!
print(result) // 3000.0
A possible optimization is to combine map
and filter
into flatMap
: 一个可能的优化是将map
和filter
组合成flatMap
:
let result = testArray.flatMap { $0[0] <= income ? $0[0] : nil }.max()!
print(result) // 3000.0
This code assumes that there is at least one matching element, otherwise last!
此代码假定至少有一个匹配元素,否则为last!
or max()!
或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")
}
Or provide a default value ( 0.0
in this example): 或提供默认值(在此示例中为0.0
):
let result = testArray.flatMap( { $0[0] <= income ? $0[0] : nil }).max() ?? 0.0
print(result) // 3000.0
Something like this: 像这样:
let testArray: [[Double]] = [
[0,0],
[1000,20.5],
[3000,21],
[3500,22.5],
[3300,21],
]
let income: Double = 3500
var closest = testArray[0][0]
var closestDif = closest - income
for innerArray in testArray {
let value = innerArray[0]
let thisDif = value - income
guard thisDif <= 0 else {
continue
}
if closestDif < thisDif {
closestDif = thisDif
closest = value
guard closestDif != 0 else {
break
}
}
}
print(closest)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.