你如何在 Swift 字典中找到前 3 个最大值? [英] How do you find the top 3 maximum values in a Swift dictionary?

查看:31
本文介绍了你如何在 Swift 字典中找到前 3 个最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I learned that I can show the key and value that is the highest in the dictionary by the code below

// 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 个值最高的英雄?示例结果将是

My question is how can I show 3 champions with the highest value? Example result would be

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

如果可能,我很想学习如何做到这一点.

I would love to learn how to do this if possible.

推荐答案

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

The max method can only return a single value. If you need to get the top 3 you would need to sort them in descending order and get the first 3 elements using prefix method

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

print(greatestChampion)


这将打印


This will print

[(key: "Neeko", value: 25), (key: "Ekko", value: 20), (key: "Ahri", value: 10)]

[(key: "Neeko", value: 25), (key: "Ekko", value: 20), (key: "Ahri", value: 10)]

这篇关于你如何在 Swift 字典中找到前 3 个最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆