二维数组中的单个元素的数学运算 - Swift
Math operations individual elements in 2D Array - Swift
我正在尝试对结合一维数组 (mod) 的二维数组 (testArray) 的各个元素执行不同的数学运算。我有以下用于生成单个变量的方法,但无法弄清楚如何将这些值返回到新的二维数组中。 Swift3.0.2.
let testArray: [[Double]] =
[[0,100,20.1],
[1,99,19.2],
[3,98,18.2],
[5,97,17.3],
[7,96,16.4],
[9,95,15.5]]
let mod: [Double] = [0,5,7,14,20,22]
//Math operations on the two above arrays
for var x in 0..<testArray.count {
var result1 = Double(testArray[x][0])
var result2 = Double(testArray[x][1] + mod[x])
var result3 = Double(testArray[x][2] - mod[x])
print(result1,result2,result3)
}
//output is as follows:
0.0 100.0 20.1
1.0 104.0 14.2
3.0 105.0 11.2
5.0 111.0 3.3
7.0 116.0 -3.6
9.0 117.0 -6.5
//how do I get the same numbers into a new 2D array as follows:
[[0.0,100.0,20.1],
[1.0,104.0,14.2],
[3.0,105.0,11.2],
[5.0,111.0,3.3],
[7.0,116.0,-3.6],
[9.0,117.0,-6.5]]
可以这么简单,
var anotherArray: [[Double]] = []
for x in 0..<testArray.count {
let result1 = Double(testArray[x][0])
let result2 = Double(testArray[x][1] + mod[x])
let result3 = Double(testArray[x][2] - mod[x])
anotherArray.append([result1, result2, result3])
}
print(anotherArray)
您可以使用 map
:
let result = testArray.indices.map { [ testArray[[=10=]][0], testArray[[=10=]][1] + mod[[=10=]], testArray[[=10=]][2] - mod[[=10=]] ] }
附带说明一下,您的 for
块可以写为:
for x in testArray.indices {
let result1 = testArray[x][0]
let result2 = testArray[x][1] + mod[x]
let result3 = testArray[x][2] - mod[x]
print(result1,result2,result3)
}
我正在尝试对结合一维数组 (mod) 的二维数组 (testArray) 的各个元素执行不同的数学运算。我有以下用于生成单个变量的方法,但无法弄清楚如何将这些值返回到新的二维数组中。 Swift3.0.2.
let testArray: [[Double]] =
[[0,100,20.1],
[1,99,19.2],
[3,98,18.2],
[5,97,17.3],
[7,96,16.4],
[9,95,15.5]]
let mod: [Double] = [0,5,7,14,20,22]
//Math operations on the two above arrays
for var x in 0..<testArray.count {
var result1 = Double(testArray[x][0])
var result2 = Double(testArray[x][1] + mod[x])
var result3 = Double(testArray[x][2] - mod[x])
print(result1,result2,result3)
}
//output is as follows:
0.0 100.0 20.1
1.0 104.0 14.2
3.0 105.0 11.2
5.0 111.0 3.3
7.0 116.0 -3.6
9.0 117.0 -6.5
//how do I get the same numbers into a new 2D array as follows:
[[0.0,100.0,20.1],
[1.0,104.0,14.2],
[3.0,105.0,11.2],
[5.0,111.0,3.3],
[7.0,116.0,-3.6],
[9.0,117.0,-6.5]]
可以这么简单,
var anotherArray: [[Double]] = []
for x in 0..<testArray.count {
let result1 = Double(testArray[x][0])
let result2 = Double(testArray[x][1] + mod[x])
let result3 = Double(testArray[x][2] - mod[x])
anotherArray.append([result1, result2, result3])
}
print(anotherArray)
您可以使用 map
:
let result = testArray.indices.map { [ testArray[[=10=]][0], testArray[[=10=]][1] + mod[[=10=]], testArray[[=10=]][2] - mod[[=10=]] ] }
附带说明一下,您的 for
块可以写为:
for x in testArray.indices {
let result1 = testArray[x][0]
let result2 = testArray[x][1] + mod[x]
let result3 = testArray[x][2] - mod[x]
print(result1,result2,result3)
}