[英]how to merge several arrays into one array with array values in Swift?
如何在 Swift 中使用數組值將多個數組合並為一個數組?
var arr1 = ["1", "2", "3"]
var arr2 = ["a", "b", "c"]
var arr3 = ["aa", "bb", "cc"]
到
[["1", "a", "aa"], ["2", "b", "bb"], ["1", "c", "cc"]]
我想你想要的是將三個數組組合成一個二維數組,然后轉置它。
要轉置二維數組,您可以在此問題中找到許多解決方案。
這在評論中使用了 Crashalot 的解決方案:
fileprivate func transpose<T>(input: [[T]]) -> [[T]] {
if input.isEmpty { return [[T]]() }
let count = input[0].count
var out = [[T]](repeating: [T](), count: count)
for outer in input {
for (index, inner) in outer.enumerated() {
out[index].append(inner)
}
}
return out
}
var arr1 = ["1", "2", "3"]
var arr2 = ["a", "b", "c"]
var arr3 = ["aa", "bb", "cc"]
transpose(input: [arr1, arr2, arr3])
如果你想要一個更快速的transpose
,你可以使用這個(從這里修改):
extension Collection where Self.Element: RandomAccessCollection {
func transposed() -> [[Self.Iterator.Element.Iterator.Element]]? {
guard Set(self.map { $0.count }).count == 1 else { return nil }
guard let firstRow = self.first else { return [] }
return firstRow.indices.map { index in
self.map{ $0[index] }
}
}
}
如果您願意,這是一種天真的表達方式。
[arr1,arr2,arr3].reduce([[],[],[]]) { result, next -> [[String]] in
return (0..<(next.count)).map{
var array = Array.init(result[$0])
array.append(next[$0]);
return array
}
}
或更直接:
[arr1,arr2,arr3].reduce(into: [[],[],[]]) { ( result : inout [[String]], next) in
_ = (0..<(next.count)).map{ result[$0].append(next[$0]);}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.