I would to know how to get key if I have the values. Which class get higher marks?
如果我有值,我会知道如何获得密钥。哪个班级得分更高?
let higherMarks = [
"ClassA": [10,20,30,40,50,60],
"ClassB": [15,25,35,45,55,65],
"ClassC": [18,28,38,48,58,68],
]
var largest = 0
var className = ""
for (classTypes, marks) in higherMarks {
for mark in marks {
if mark > largest {
largest = mark
}
}
}
print(largest)
1 个解决方案
#1
2
What I'm saying in my comment is that you need to get the classTypes
when you get the mark
. Because when you get the higher mark, you want to also get the corresponding key value.
我在评论中说的是,你得到标记时需要获得classTypes。因为当您获得更高的分数时,您还希望获得相应的键值。
Keeping your code's logic I would do something like this:
保持代码的逻辑我会做这样的事情:
let higherMarks = [
"ClassA": [10,20,30,40,50,60],
"ClassB": [15,25,35,45,55,65],
"ClassC": [18,28,38,48,58,68],
]
func findBestClass(in results: [String: [Int]]) -> (name: String, score: Int) {
var largest = 0
var type = ""
for (classType, marks) in results {
if let max = marks.max(), max > largest {
largest = max
type = classType
}
}
return (type, largest)
}
let best = findBestClass(in: higherMarks)
print("The best class is \(best.name) with a score of \(best.score).")
I just replaced your inner loop with .max()
and changed the name of the key variable because it should not be plural. My method also returns a tuple because I find it relevant in this situation. But I didn't change your logic, so you can see what I meant by "also get the classTypes".
我只是用.max()替换你的内部循环并更改了键变量的名称,因为它不应该是复数。我的方法也返回一个元组,因为我发现它在这种情况下是相关的。但是我并没有改变你的逻辑,所以你可以看到我的意思“也得到了classTypes”。
#1
2
What I'm saying in my comment is that you need to get the classTypes
when you get the mark
. Because when you get the higher mark, you want to also get the corresponding key value.
我在评论中说的是,你得到标记时需要获得classTypes。因为当您获得更高的分数时,您还希望获得相应的键值。
Keeping your code's logic I would do something like this:
保持代码的逻辑我会做这样的事情:
let higherMarks = [
"ClassA": [10,20,30,40,50,60],
"ClassB": [15,25,35,45,55,65],
"ClassC": [18,28,38,48,58,68],
]
func findBestClass(in results: [String: [Int]]) -> (name: String, score: Int) {
var largest = 0
var type = ""
for (classType, marks) in results {
if let max = marks.max(), max > largest {
largest = max
type = classType
}
}
return (type, largest)
}
let best = findBestClass(in: higherMarks)
print("The best class is \(best.name) with a score of \(best.score).")
I just replaced your inner loop with .max()
and changed the name of the key variable because it should not be plural. My method also returns a tuple because I find it relevant in this situation. But I didn't change your logic, so you can see what I meant by "also get the classTypes".
我只是用.max()替换你的内部循环并更改了键变量的名称,因为它不应该是复数。我的方法也返回一个元组,因为我发现它在这种情况下是相关的。但是我并没有改变你的逻辑,所以你可以看到我的意思“也得到了classTypes”。