按值SWIFT将数组拆分为数组

ruyhziif  于 2022-09-19  发布在  Swift
关注(0)|答案(4)|浏览(189)

我有一个包含如下数据的数组:[值]#模式

我想按[模式]将此数组拆分为[Value]数组,但保留数据的相同位置,以便可以为同一模式的多个数组:

例如:

let array = ["23.88", "24", "30",  "24.16#C", "25#C", "12#C", "24.44#O", "50#O" , "31", "40" , "44#C", "55#C"]  

// Result 

No mode  ---> [23.88,24,30] 
mode = C ---> [24.16,25,12]
mode = O ---> [24.44,50]
No mode  ---> [31,40] 
mode = C ---> [44,55]

我试过这个扩展,但不是我想要的

extension SequenceType {
    func groupBy<U : Hashable>(@noescape keyFunc: Generator.Element -> U) -> [U:[Generator.Element]] {
        var dict: [U:[Generator.Element]] = [:]
        for el in self {
            let key = keyFunc(el)
            if case nil = dict[key]?.append(el) { dict[key] = [el] }
        }
        return dict
    }
}

它给出了如下结果:

No mode  ---> [23.88,24,30,31,40] 
mode = C ---> [24.16,25,12,44,55]
mode = O ---> [24.44,50]
dly7yett

dly7yett1#

我建议您使用带元组的数组(用来保存键)。组成此数组,然后您可以轻松地将其重新Map为您需要的格式:

let array = ["23.88", "24", "30",  "24.16#C", "25#C", "12#C", "24.44#O", "50#O" , "31", "40" , "44#C", "55#C"]

let noModeTag = "#NoMode"

func group(array: [String]) -> [(String, [Double])]
{
    var result = [(String, [Double])]()

    func addNextElement(number: Double?, _ mode: String?) {
        guard let number = number, mode = mode else {fatalError("input format error")}
        if result.last?.0 == mode {
            var array = result.last!.1
            array.append(number)
            result[result.count - 1] = (mode, array)
        } else {
            result.append((mode, [number]))
        }
    }

    for element in array {
        if element.containsString("#") {
            let separated = element.componentsSeparatedByString("#")
            addNextElement(Double(separated.first ?? "_"), separated.last)
        } else {
            addNextElement(Double(element), noModeTag)
        }
    }
    return result
}

print(group(array))
//[("#NoMode", [23.88, 24.0, 30.0]), ("C", [24.16, 25.0, 12.0]), ("O", [24.44, 50.0]), ("#NoMode", [31.0, 40.0]), ("C", [44.0, 55.0])]
uajslkp6

uajslkp62#

您需要修改groupBy扩展以分组到一个2元组数组而不是字典中,其中第一个元组元素对应于一个非唯一的“key”,第二个tuple元素是self数组中可归类到给定键的后续元素的数组。

  • 修改SequenceType扩展名*
extension SequenceType {
    func groupBy<U : Comparable>(@noescape keyFunc: Generator.Element -> U) -> [(U,[Generator.Element])] {
        var tupArr: [(U,[Generator.Element])] = []
        for el in self {
            let key = keyFunc(el)
            if tupArr.last?.0 == key {
                tupArr[tupArr.endIndex-1].1.append(el)
            }
            else {
                tupArr.append((key,[el]))
            }
        }
        return tupArr
    }
}

另请注意,现在扩展中的通用U符合Comparable就足够了,因为我们只使用U元素作为元组中的“伪”键。

  • 调用分机*

通过此修改,我们可以将groupBy(..)方法调用为

let array = ["23.88", "24", "30",  "24.16#C", "25#C", "12", "24.44", "50" , "31#O", "40#O" , "44#C", "55#C"]

/* assuming we know the last character always describe the mode,
   given one is included (#) */
let groupedArray: [(String,[String])] = array.groupBy {
    guard B1a1a1b.characters.contains("#") else { return "No mode" }
    return "mode = " + String(B1a1a1b.characters.last!)
}

print(groupedArray)
/* [("No mode", ["23.88", "24", "30"]), 
    ("mode = C", ["24.16#C", "25#C"]), 
    ("No mode", ["12", "24.44", "50"]), 
    ("mode = O", ["31#O", "40#O"]), 
    ("mode = C", ["44#C", "55#C"])] */
  • 从分组数组中删除原始模式标记(#X)*

如果希望删除结果数组中的原始模式标记(#X),可以在调用groupBy之后应用额外的map操作。

删除结果值为String的标记:

let groupedArrayClean = groupedArray.map { (B1a2a1b.0, B1a2a1b.1.map {
    String(B1a2a1b.characters.prefixUpTo(B1a2a1b.characters.indexOf("#") ?? B1a2a1b.characters.endIndex))
    })
}

print(groupedArrayClean)
/* [("No mode", ["23.88", "24", "30"]), 
    ("mode = C", ["24.16", "25"]), 
    ("No mode", ["12", "24.44", "50"]), 
    ("mode = O", ["31", "40"]), 
    ("mode = C", ["44", "55"])] */

或者,结果值为Double

let groupedArrayClean = groupedArray.map { (B1a3a1b.0, B1a3a1b.1.flatMap {
    Double(
        String((B1a3a1b.characters.prefixUpTo(B1a3a1b.characters.indexOf("#") ?? B1a3a1b.characters.endIndex))))
    })
}

print(groupedArrayClean)
/* [("No mode", [23.879999999999999, 24.0, 30.0]), 
    ("mode = C", [24.16, 25.0]), 
    ("No mode", [12.0, 24.440000000000001, 50.0]), 
    ("mode = O", [31.0, 40.0]), 
    ("mode = C", [44.0, 55.0])] */
  • 或者:在单链调用中分组和清理模式标记*

或者,同时执行groupBymap,无需中间赋值:

let groupedArrayClean: [(String,[String])] = array.groupBy {
    guard B1a4a1b.characters.contains("#") else { return "No mode" }
    return "mode = " + String(B1a4a1b.characters.last!)
    }
    .map { (B1a4a1b.0, B1a4a1b.1.map {
        String(B1a4a1b.characters
            .prefixUpTo(B1a4a1b.characters.indexOf("#") ?? B1a4a1b.characters.endIndex))
        })
}

(类似于生成的Double值的情况。)

e4yzc0pl

e4yzc0pl3#

请看下面的代码:

func newArray(incomeArray:[String], index: Int) -> [String: [String]] {
    let modeArray = incomeArray[index].componentsSeparatedByString("#")
    let currentMode = modeArray.count > 1 ? modeArray.last : "No mode"
    var arr: [String] = []
    for i in index...incomeArray.count-1 {
        let modeArray = incomeArray[i].componentsSeparatedByString("#")
        let mode = modeArray.count > 1 ? modeArray.last : "No mode"
        if mode == currentMode || (mode == "" && currentMode == "") {
            arr.append(modeArray.first!)
        } else {
            break
        }
    }
    return ["Mode = " + currentMode!: arr];
}

let array: [String] = ["23.88", "24", "30",  "24.16#C", "25#C", "12", "24.44", "50" , "31#O", "40#O" , "44#C", "55#C"]

var index = 0
while index < array.count {
    let dict = newArray(array, index: index)
    print(dict)
    index += dict[Array(dict.keys).first!]!.count
}

结果:

["Mode = No mode": ["23.88", "24", "30"]]
["Mode = C": ["24.16", "25"]]
["Mode = No mode": ["12", "24.44", "50"]]
["Mode = O": ["31", "40"]]
["Mode = C": ["44", "55"]]
sg24os4d

sg24os4d4#

六年后,仍然没有简单的方法来获得这种细分。至少我不知道有什么。我今天遇到了这个问题,以下是我是如何解决这个问题的(2022年,使用SWIFT 5+)。

实施是Collection的扩展:

extension Collection {
    func segments<Eq: Equatable>(_ key: @escaping (Element) -> Eq) -> AnySequence<SubSequence> {
        AnySequence { () -> AnyIterator<SubSequence> in
            var idx = startIndex
            var prevKey: Eq?

            return AnyIterator {
                guard idx < endIndex else { return nil }

                let subSequence = self[idx ..< endIndex]
                    .prefix { element in
                        let elementKey = key(element)
                        defer {prevKey = elementKey}

                        if let prevKey = prevKey {
                            return prevKey == elementKey
                        } else {
                            return true
                        }
                    }
                idx = index(idx, offsetBy: subSequence.count, limitedBy: endIndex) ?? endIndex
                return subSequence
            }
        }
    }
}

使用它是一个简单的一行程序,如下面的测试用例所示:

struct ElementOptionalKey: Equatable {
        let key: String?
        let value: Double
    }

    func testArraySplitterOptionalKey() throws {
        let array: [ElementOptionalKey] = [
            ElementOptionalKey(key: "1", value: 1.0),
            ElementOptionalKey(key: "1", value: 1.1),
            ElementOptionalKey(key: "2", value: 2.0),
            ElementOptionalKey(key: "2", value: 2.1),
            ElementOptionalKey(key: nil, value: 0.0),
            ElementOptionalKey(key: nil, value: 0.1),
            ElementOptionalKey(key: "1", value: 1.2),
            ElementOptionalKey(key: "1", value: 1.3),
            ElementOptionalKey(key: "1", value: 1.4),
            ElementOptionalKey(key: nil, value: 0.2),
            ElementOptionalKey(key: "3", value: 3.0)
        ]

        // HERE is the line :-)
        let result = array.segments { B1a1a1b.key }

        XCTAssertEqual(Array(result), [
            [ElementOptionalKey(key: "1", value: 1.0), ElementOptionalKey(key: "1", value: 1.1)],
            [ElementOptionalKey(key: "2", value: 2.0), ElementOptionalKey(key: "2", value: 2.1)],
            [ElementOptionalKey(key: nil, value: 0.0), ElementOptionalKey(key: nil, value: 0.1)],
            [ElementOptionalKey(key: "1", value: 1.2), ElementOptionalKey(key: "1", value: 1.3), ElementOptionalKey(key: "1", value: 1.4)],
            [ElementOptionalKey(key: nil, value: 0.2)],
            [ElementOptionalKey(key: "3", value: 3.0)]
        ])
    }

我使用空集合,甚至使用可选的键进行了测试,就像您在原始问题中所做的那样。效果很好。

相关问题