如何在Swift中遍历字典以找到Key-Value对中的最高值?

huangapple go评论45阅读模式
英文:

How do I iterate through a dictionary to find the highest value from a Key-Value pair using Swift?

问题

以下是您的代码的翻译部分:

我正在进行一个编程练习,想要编写一个能够筛选字典并返回具有最高分数的人的名字以及他们的分数的代码。这个问题涉及到可选项,我希望在我的解决方案中考虑到这一点。以下是示例问题:

如果你有一个包含3个学生姓名和他们的考试分数的字典,你能打印出最高分吗?
例如,如果
studentsAndscores = ["Amy": 88, "James": 55, "Helen": 99]
那么你的函数应该打印出 99
但你不知道分数是多少,所以你的程序必须处理所有可能性!
提示:当你使用键从字典中获取值时,取出的值是一个可选项!

以下是我经过多次尝试后目前为止的代码。尽管我还没有能够接近一个解决方案。我遇到了几种不同的错误,使我无法理解。

这是我的代码:

给定 -> var studentsAndScores = ["Amy": Int(readLine()!)!, "James": Int(readLine()!)!, "Helen": Int(readLine()!)!]

给定 -> func highestScore(scores: [String: Int]) {

// 在这里编写你的代码。(以下是我的代码)
for value in studentsAndScores.values {
if studentsAndScores[value] == 99 {
return("Key": String, Value: Int)
} else {
return(false)
}
}

}

请注意,您的代码存在一些问题,需要进行修正。如果您需要更多帮助,请随时提出具体问题。

英文:

I am working on a coding exercise and would like to write a code that can sift through the dictionary and return the name of the person with the highest score along with their score. This problem uses optionals and I want to ensure that I account for this within my solution? Here is the problem for example:

If you have a dictionary with 3 student names and their test scores, can you print the highest score?
e.g. if
studentsAndscores = ["Amy": 88, "James": 55, "Helen": 99]
Then your function should print 99.
But you don't know what the scores are, so your program has to handle all possibilities!
Hint: When you get the value out of a dictionary using a key, the value that comes out is an Optional!

Here is what I had so far after trying a dozen times. Although, I haven't been able to come close to a solution. I gotten a couple different errors that prevent me from understanding.

Here's my code:

given -> var studentsAndScores = ["Amy": Int(readLine()!)!, "James": Int(readLine()!)!, "Helen": Int(readLine()!)!]

given ->func highestScore(scores: [String: Int]) {
  
  //Write your code here. (My code below)
  for value in studentsAndScores.values {
  if studentsAndScores[value] == 99 {
      return("Key": String, Value: Int) 
  } else {
      return(false)
  }
  }
  
  
}```


</details>


# 答案1
**得分**: 1

以下是您要翻译的内容:

你可以这样做。这种方法假设学生不能获得负分。在函数内部,它将0选择为学生可以获得的最低分值。然后,每次达到高于先前找到的最大值的值时,它会更新最大值。因为这使用了'>'而不是'>=',所以它将返回找到的第一个具有最高分的人以及最高分。

方法是循环遍历字典的所有键值对,在您的示例中是"Amy"、"James"和"Helen",然后检查每个人得分。我将键命名为"student",值命名为"scoreValue"。

我在示例中使用了您提供的值,而不是提供的"Int(readLine()!)!",但那只是为了更容易演示。如果这些函数能正确给出数字,那么字典迭代应该能起作用。

祝你在Swift中好运!

```swift
var studentsAndScores = ["Amy": 88, "James": 55, "Helen": 99]

func highestScore(scores: [String: Int]) {
    var studentWithMaxScore: String = ""
    var maxValue: Int = -1 // 这假设没有人会得分低于0。
    
    for (student, scoreValue) in studentsAndScores {
        if scoreValue > maxValue {
            maxValue = scoreValue
            studentWithMaxScore = student
        }
    }
    
    // 在你尝试字典中的所有键后,你的临时变量应该保存拥有最高分的学生的姓名和最高分值。
    print("学生最高分: \(studentWithMaxScore)")
    print("分数: \(maxValue)")
}

// 这是在提供的字典上调用函数。
highestScore(scores: studentsAndScores)

注意:已经将代码中的HTML实体引号(如&quot;)替换为正常的双引号。

英文:

You can do something like this. This approach assumes that a student can't have a negative test score. Inside the function, it choses 0 as the lowest value that a student can have. It then updates the maximum value each time that it reaches a value that is higher than the previously found maximum. because this uses '>' and not '>=' this will return the first person to found with the maximum score and the maximum score.

The approach is to loop through all of the key value pairs of the dictionary, in your example this was "Amy", "James", and "Helen", and then to check the score that each of them got. I named the key "student" and the value "scoreValue".

I used the values that you provided in your example instead of the "Int(readLine()!)!" that were provided, but that was just for easier demonstration. If those functions give you numbers correctly, then the dictionary iteration should do the trick.

Good luck with Swift!

var studentsAndScores = [&quot;Amy&quot;: 88, &quot;James&quot;: 55, &quot;Helen&quot;: 99]


func highestScore(scores: [String: Int]) {
    var studentWithMaxScore: String = &quot;&quot;
    var maxValue: Int = -1 // This assumes that no one will score less than 0.
    
    for (student, scoreValue) in studentsAndScores {
        if scoreValue &gt; maxValue {
            maxValue = scoreValue
            studentWithMaxScore = student
        }
    }
    
    //After you have tries all of the keys in the dictionary, your temporary variables should hold the name the student with the highest score and the highest score respectively.
    print(&quot;Student with highest score: \(studentWithMaxScore)&quot;)
    print(&quot;Score: \(maxValue)&quot;)
    
}

//This is calling the function on the dictionary provided. 
highestScore(scores: studentsAndScores)

答案2

得分: 1

I would just use a for loop and check/set if the score is higher than the previous one; something like this:

var studentsAndScores = ["Amy": 88, "James": 55, "Helen": 99, "Dan": 30]

var highestScore = 0
var studentWithHighestScore = ""

for (student, score) in studentsAndScores {
    if score > highestScore {
        highestScore = score
        studentWithHighestScore = student
    }
}
英文:

I would just use a for loop and check/set if the score is higher than the previous one; something like this:

var studentsAndScores = [&quot;Amy&quot;: 88, &quot;James&quot;: 55, &quot;Helen&quot;: 99, &quot;Dan&quot;:30]

var highestScore = 0
var studentWithHighestScore = &quot;&quot;

for (student, score) in studentsAndScores {
    if score &gt; highestScore {
        highestScore = score
        studentWithHighestScore = student
    }
}

答案3

得分: 1

以下是您要翻译的内容:

You can try as below:

var students = ["Amy": 88, "James": 55, "Helen": 99]

func highestScore(students: [String: Int]) -> Dictionary<String, Int>.Element? {
    return students.max(by: { $0.value < $1.value })
}

//Print the person with the highest score
if let topStudent = highestScore(students: students) {
    print("\(topStudent.key) has the highest score of \(topStudent.value)")
}

But I recommend you should revise your code as follows to more clearly:

struct Student {
    var name: String
    var score: Int
}

var students = [
    Student(name: "Amy", score: 88),
    Student(name: "James", score: 55),
    Student(name: "Helen", score: 99),
]

func highestScore(students: [Student]) -> Student? {
    return students.max(by: { $0.score < $1.score })
}

//Print the person with the highest score
if let topStudent = highestScore(students: students) {
    print("\(topStudent.name) has the highest score of \(topStudent.score)")
}
英文:

You can try as below:

var students = [&quot;Amy&quot;: 88, &quot;James&quot;: 55, &quot;Helen&quot;: 99]

func highestScore(students: [String: Int]) -&gt; Dictionary&lt;String, Int&gt;.Element? {
    return students.max(by: { $0.value &lt; $1.value })
}

//Print the person with the highest score
if let topStudent = highestScore(students: students) {
    print(&quot;\(topStudent.key) has the highest score of \(topStudent.value)&quot;)
}

But I recommend you should revise your code as follows to more clearly:

struct Student {
    var name: String
    var score: Int
}

var students = [
    Student(name: &quot;Amy&quot;, score: 88),
    Student(name: &quot;James&quot;, score: 55),
    Student(name: &quot;Helen&quot;, score: 99),
]

func highestScore(students: [Student]) -&gt; Student? {
    return students.max(by: { $0.score &lt; $1.score })
}

//Print the person with the highest score
if let topStudent = highestScore(students: students) {
    print(&quot;\(topStudent.name) has the highest score of \(topStudent.score)&quot;)
}

huangapple
  • 本文由 发表于 2023年5月11日 06:47:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定