如何使用Swift遍历字典以找到Key-Value对中的最大值?

ykejflvf  于 2023-05-16  发布在  Swift
关注(0)|答案(3)|浏览(181)

我正在进行编码练习,想写一段代码,可以通过字典筛选,并返回得分最高的人的名字沿着他们的分数。这个问题使用了可选选项,我想确保在我的解决方案中考虑到了这一点?下面是一个例子:
如果你有一本字典,上面有3个学生的名字和他们的考试成绩,你能打印出最高的分数吗?例如,如果studentsAndscores = [“Amy”:88,“詹姆斯”:55,“海伦”:99]然后你的函数应该打印99。但是你不知道分数是多少,所以你的程序必须处理所有的可能性!提示:当你使用一个键从字典中获取值时,得到的值是一个Optional!
这是我在尝试了十几次之后得到的。不过,我还没找到解决办法。我得到了几个不同的错误,使我无法理解。
下面是我的代码:

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)
  }
  }
  
  
}```
qnzebej0

qnzebej01#

你可以尝试如下:

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)")
}

但是我建议你应该修改你的代码,如下所示:

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)")
}
qacovj5a

qacovj5a2#

你可以这样做。这种方法假设学生不能有一个负的测试分数。在函数内部,它选择0作为学生可以拥有的最低值。然后,每当它达到高于先前找到的最大值的值时,它更新最大值。因为这使用'>'而不是'>=',这将返回第一个找到最大分数的人和最大分数。
方法是循环遍历字典的所有键值对,在示例中是“Amy”、“James”和“Helen”,然后检查每个键值对的得分。我将键命名为“student”,将值命名为“scoreValue”。
我使用了您在示例中提供的值,而不是“Int(readLine()!)!”,但那只是为了更容易演示。如果这些函数正确地给予了数字,那么字典迭代应该可以完成任务。
祝Swift好运!

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

func highestScore(scores: [String: Int]) {
    var studentWithMaxScore: String = ""
    var maxValue: Int = -1 // This assumes that no one will score less than 0.
    
    for (student, scoreValue) in studentsAndScores {
        if scoreValue > 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("Student with highest score: \(studentWithMaxScore)")
    print("Score: \(maxValue)")
    
}

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

mrzz3bfm3#

我只需要使用一个for循环并检查/设置分数是否高于前一个;就像这样:

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
    }
}

相关问题