簡體   English   中英

Swift-字典的排序和分離數組

[英]Swift - sorting and separating array of dictionaries

有沒有一種方法可以根據參數值對字典數組進行有效排序,並為每個參數值返回單獨的數組?

示例數組:

[["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進行訪問,也可以使用keyskeys進行排序,然后深入研究每個數組。

派生單個排序的數組是微不足道的。

這不是一個漂亮的實現,看起來確實可行,但不確定是否比您的快:

let array: [[String: String]] = [["value":"3", "groupID":"1"],
             ["value":"5", "groupID":"2"],
             ["value":"2", "groupID":"1"],
             ["value":"6", "groupID":"3"],
             ["value":"1", "groupID":"2"],
             ["value":"9", "groupID":"3"]]

// grouping
var dict: [String: [[String: String]]] = [:]
array.forEach { (element) in
    var elements: [[String: String]] = []
    let groupID = element["groupID"]!
    if dict.keys.contains(groupID) {
        elements = dict[groupID]!
    }
    elements.append(element)
    dict[groupID] = elements
}

// spliting and sorting
var final: [[String: [[String: String]]]] = []
dict.keys.sorted().forEach { (key) in
    let sorted = dict[key]!.sorted(by: { $0["value"]! < $1["value"]! })
    final.append([key: sorted])
}

print(final)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM