代码之家  ›  专栏  ›  技术社区  ›  Wesly

如何在Swift字典中找到前3个最大值?

  •  0
  • Wesly  · 技术社区  · 5 年前

    我了解到我可以通过下面的代码显示字典中最高的键和值

    // champions dictionary
    var champions = ["Ekko": 20, "Ahri": 10, "Vayne": 2, "Neeko": 25, "Zed": 6]
    
    let greatestChampion = champions.max { a, b in a.value < b.value }
    print greatestChampion // optional(("Ekko": 20))
    
    

    我的问题是,如何才能显示3个冠军与最高的价值?示例结果是

    print greatestChampion // optional(("Ekko": 20, "Neeko": 25, "Ahri": 10))
    

    如果可能的话,我很想学怎么做。

    2 回复  |  直到 5 年前
        1
  •  3
  •   Leo Dabus    5 年前

    max方法只能返回一个值。如果需要获取前3个元素,则需要按降序对它们进行排序,并使用prefix方法获取前3个元素


    let greatestChampion = champions.sorted { $0.value > $1.value }.prefix(3)
    
    print(greatestChampion)
    

    这将打印

        2
  •  2
  •   Ryan    5 年前

    利奥直截了当的方法很管用。或者,你可以在苹果的Swift算法repo中看到一个性能更好的实现。

    Code

    Explanation and Performance

    Tests