gpt4 book ai didi

ios - 将[[((Int,String)]]]组合成[(Int,String)]的优雅方法?

转载 作者:行者123 更新时间:2023-12-01 18:38:18 26 4
gpt4 key购买 nike

我正在使用Swift 4,Xcode 9。

具体来说,我有一个数组[[((Int,String)]]的数组,其中Int是一个等级,而String是一个Name + Items ...,它们使用.joined(separator:“;”)组合在一起。

数据可能如下所示:

[[1,"My Name;Item1;Item2"], [(5,"My Name;Item2;Item3"), (3,"My Second Name;Item1")]]

我想组合内部数组,以便:
  • Int根据名称(最多“;”)添加匹配项
  • 字符串添加后续项(如果尚不存在)

  • 结合我上面的示例应导致此:
    [(6,"My Name;Item1;Item2;Item3"), (3,"My Second Name;Item1")]

    即输入为 [[(Int, String)]],输出为 [(Int, String)]
    目前,我可以通过一组相当复杂的循环来实现这一目标。对于大型数据集,这会导致明显的性能下降。是否有一种优雅/简单的方式来组合我要求的这些数组?

    感谢您的指导!

    最佳答案

    (通常,我会对此发表评论,因为它不能回答问题,但是确切解释您应该如何更改此问题是值得的。)

    当然有可能,但是没有。答案是将其替换为结构数组。根据您的数据描述:

    struct Element {
    let rank: Int
    let name: String
    let items: Set<String> // Since you seem to want them to be unique and unordered
    }

    let elements: [[Element]] =
    [[Element(rank: 1, name: "My Name", items: ["Item1", "Item2"])],
    [Element(rank: 5, name: "My Name", items: ["Item2", "Item3"]),
    Element(rank: 3, name: "My Second Name", items: ["Item1"])]]

    // You want to manage these by name, so let's make key/value pairs of all the elements
    // as (Name, Element)
    let namedElements = elements.joined().map { ($0.name, $0) }

    // Now combine them as you describe. Add the ranks, and merge the items
    let uniqueElements =
    Dictionary<String, Element>(namedElements,
    uniquingKeysWith: { (lhs, rhs) -> Element in
    return Element(rank: lhs.rank + rhs.rank,
    name: lhs.name,
    items: lhs.items.union(rhs.items))
    })

    // The result is the values of the dictionary
    let result = uniqueElements.values

    // Element(rank: 6, name: "My Name", items: Set(["Item3", "Item2", "Item1"]))
    // Element(rank: 3, name: "My Second Name", items: Set(["Item1"]))

    关于ios - 将[[((Int,String)]]]组合成[(Int,String)]的优雅方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47626437/

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