我有一個陣列,我想合并它。
這是陣列:
let numbers = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
我需要這樣的輸出:
let result = [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ]
uj5u.com熱心網友回復:
let numbers = [[1,2,3], [4,5,6]]
let result = zip(numbers[0], numbers[1]).map { [$0.0, $0.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 { $0[n] })
}
print(result) // -> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
uj5u.com熱心網友回復:
您可以使用 zip 全域函式,該函式給定 2 個序列,回傳一個元組序列,然后使用適當的 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452649.html
上一篇:為什么在使用CupertinoNavigationBarBackButton時出現Flutter錯誤螢屏(紅屏)?
下一篇:在Kotlin中傳遞值作為參考
