【问题标题】:Merge several arrays into one array如何在 Swift 中将多个数组合并为一个具有数组值的数组?
【发布时间】:2019-02-27 02:13:38
【问题描述】:

如何在 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"]]

【问题讨论】:

  • 你的意思是["3", "c", "cc"] 是最后一个子数组?
  • 欢迎来到 StackOverflow。请展示您已经尝试过的内容、无效的内容、代码示例等。请阅读How to Askminimal reproducible example,然后阅读edit 您的问题,其中显示了说明问题的最小 代码.
  • 子数组的长度是否相同?

标签: ios arrays swift


【解决方案1】:

如果你愿意,这是一种幼稚的表达方式。

[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]);}
 }

【讨论】:

    【解决方案2】:

    我想你想要的是将三个数组组合成一个二维数组,然后转置它。

    要转置二维数组,您可以在此question 中找到许多解决方案。

    这在 cmets 中使用了 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,可以使用这个(修改自here):

    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] }
            }
        }
    }
    

    【讨论】:

    • 所有子数组的计数必须相同
    • input 必须具有矩阵形式。为了使转置工作,所有内部数组必须具有相同数量的元素。
    • @Carpsen90 但是 OP 没有说明当数组长度不同时会发生什么,所以我没有处理这个问题。当它们的长度不同时,您认为输出应该是什么?
    • 一些使用默认值的填充可能会有所帮助(用数学术语来说,所有向量(数组)确实必须具有相同数量的坐标,甚至不应该允许)
    • guard input.dropFirst().first(where: {$0.count != input[0].count}) == nil else { fatalError("All arrays have to have the same number of elements") }
    猜你喜欢
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2015-11-11
    • 2017-01-11
    • 1970-01-01
    相关资源
    最近更新 更多