gpt4 book ai didi

ios - 按值 Swift 将数组拆分为数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:18:34 24 4
gpt4 key购买 nike

我有一个包含如下数据的数组:[value]#[mode](mode 是可选的)

我想通过 [mode] 将此数组拆分为 [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]

最佳答案

我建议您使用数组和元组(保存键)。组成这个数组,然后您可以轻松地将其重新映射为您需要的格式:

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

关于ios - 按值 Swift 将数组拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38921864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com