How to transpose an array of strings

前端 未结 3 541
伪装坚强ぢ
伪装坚强ぢ 2020-12-20 20:23

I\'ve a txt including some data in the following format.

AYGA:GKA:GOROKA:GOROKA:PAPUA NEW GUINEA:06:04:54:S:145:23:30:E:5282
AYLA:LAE::LAE:PAPUA NEW GUINEA:0         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-20 20:56

    Perhaps more generically (and with a zip like behaviour):

    extension Sequence where
        Element: Collection,
        Element.Index == Int,
        Element.IndexDistance == Int
    {
        public func transposed(prefixWithMaxLength max: Int = .max) -> [[Element.Element]] {
            var o: [[Element.Element]] = []
            let n = Swift.min(max, self.min{ $0.count < $1.count }?.count ?? 0)
            o.reserveCapacity(n)
            for i in 0 ..< n {
                o.append(map{ $0[i] })
            }
            return o
        }
    }
    

    Now we can use it like so:

    [0..<5, 10..<20, 100..<200]
        .map(Array.init)
        .transposed()
    

    ... which returns:

    [[0, 10, 100], [1, 11, 101], [2, 12, 102], [3, 13, 103], [4, 14, 104]]
    

提交回复
热议问题