gpt4 book ai didi

arrays - Swift - 排序和分离字典数组

转载 作者:行者123 更新时间:2023-11-28 11:59:26 26 4
gpt4 key购买 nike

有没有一种方法可以根据参数值对字典数组进行高效排序,并为每个参数值返回单独的数组?

示例数组:

[["value":3, "groupID":1],
["value":5, "groupID":2],
["value":2, "groupID":1],
["value":6, "groupID":3],
["value":1, "groupID":2],
["value":9, "groupID":3]]

期望的返回输出 1(排序数组):

[["value":2, "groupID":1],
["value":3, "groupID":1],
["value":1, "groupID":2],
["value":5, "groupID":2],
["value":6, "groupID":3],
["value":9, "groupID":3]]

期望的返回输出2(按参数分隔的数组):

[["value":2, "groupID":1],
["value":3, "groupID":1]]

[["value":1, "groupID":2],
["value":5, "groupID":2]]

[["value":6, "groupID":3],
["value":9, "groupID":3]]

我想出的一个解决方案很慢,它是:

//variable array is the master array of dictionaries

var sorted = [[Int:Int]]()
//(Output 1) sorted is the sorted array
sorted = array.sorted { t1, t2 in
if t1.groupID == t2.groupID {
return t1.value < t2.value
}
return t1.groupID < t2.groupID
}

var separated = [Int:[Int:Int]]()
//(Output 2) separated is a dictionary that contains separate arrays, all of which have the same of a designated property. Essentially the same thing as separate, distinct arrays sorted by parameter for Output 2
separated = [
for i in 0..<sorted.count {
separated[sorted[i].channel]?.append(sorted[i])
}

有没有想过如何让它更快?谢谢!

最佳答案

这是一个简单的单行方法,可以帮助您入门:

let d = Dictionary.init(grouping: array) {$0["groupID"]!}

结果是一个字典,以 groupID 的值作为键:

["1": [["groupID": "1", "value": "3"], ["groupID": "1", "value": "2"]],
"2": [["groupID": "2", "value": "5"], ["groupID": "2", "value": "1"]],
"3": [["groupID": "3", "value": "6"], ["groupID": "3", "value": "9"]]]

好吧,想想那个结果。字典的 是您的三个“期望输出”数组:

[["value":"2", "groupID":"1"],
["value":"3", "groupID":"1"]]

[["value":"1", "groupID":"2"],
["value":"5", "groupID":"2"]]

[["value":"6", "groupID":"3"],
["value":"9", "groupID":"3"]]

您可以将值作为字典的 values 访问,或者您可以使用 keys 按键排序,然后深入每个数组。

导出单个排序数组很简单。

关于arrays - Swift - 排序和分离字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50356720/

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