合并 Swift 中的子数组
Merge sub-array in Swift
我有一个数组,我想合并它。
这是数组:
let numbers = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
我需要这样的输出:
let result = [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
你可以使用 zip 全局函数,给定 2 个序列,returns 一个元组序列,然后使用适当的 init 获得一个元组数组。
var xAxis = [1, 2, 3, 4]
var yAxis = [2, 3, 4, 5]
let pointsSequence = zip(xAxis, yAxis)
let chartPoints = Array(pointsSequence)
print(chartPoints)
然后您可以像这样访问元组:
let point = chartPoints[0]
point.0 // This is the 1st element of the tuple
point.1 // This is the 2nd element of the tuple
let numbers = [[1,2,3], [4,5,6]]
let result = zip(numbers[0], numbers[1]).map { [[=10=].0, [=10=].1]}
print(result) // -> [[1, 4], [2, 5], [3, 6]]
如果数组有更多元素,下面的方法就可以了。
let numbers = [[1,2,3], [4,5,6], [7,8,9]]
var result : [[Int]] = []
for n in 0...numbers.first!.count-1{
result.append(numbers.compactMap { [=11=][n] })
}
print(result) // -> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
我有一个数组,我想合并它。
这是数组:
let numbers = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
我需要这样的输出:
let result = [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
你可以使用 zip 全局函数,给定 2 个序列,returns 一个元组序列,然后使用适当的 init 获得一个元组数组。
var xAxis = [1, 2, 3, 4]
var yAxis = [2, 3, 4, 5]
let pointsSequence = zip(xAxis, yAxis)
let chartPoints = Array(pointsSequence)
print(chartPoints)
然后您可以像这样访问元组:
let point = chartPoints[0]
point.0 // This is the 1st element of the tuple
point.1 // This is the 2nd element of the tuple
let numbers = [[1,2,3], [4,5,6]]
let result = zip(numbers[0], numbers[1]).map { [[=10=].0, [=10=].1]}
print(result) // -> [[1, 4], [2, 5], [3, 6]]
如果数组有更多元素,下面的方法就可以了。
let numbers = [[1,2,3], [4,5,6], [7,8,9]]
var result : [[Int]] = []
for n in 0...numbers.first!.count-1{
result.append(numbers.compactMap { [=11=][n] })
}
print(result) // -> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]