我想获得这些学生最受欢迎的主题,我不知道如何以至少一种优雅的方式解决这个问题。我想不出怎么查字典。它应该以最常见的答案返回主题。
student = {
1: {"name": "A", "grade": 10, "subject": "sports"},
2: {"name": "B", "grade": 12, "subject": "maths"},
3: {"name": "C", "grade": 8, "subject": "german"},
4: {"name": "D", "grade": 11, "subject": "maths"},
5: {"name": "E", "grade": 6, "subject": "art"},
6: {"name": "F", "grade": 9, "subject": "english"}
}
这是我已经尝试过的事情的开始,但不知道如何继续,因为我不知道如何寻找最大的变量:
for key in student:
if student[key]["subject"] == "sports":
favorite_sports += 1
elif student[key]["subject"] == "maths":
favorite_maths += 1
elif student[key]["subject"] == "german":
favorite_german += 1
elif student[key]["subject"] == "art":
favorite_art += 1
elif student[key]["subject"] == "enlgish":
favorite_english += 1
我不知道如何以一种好的方式寻找最大的变量…
可以使用collection中的Counter类:
student = {
1: {"name": "A", "grade": 10, "subject": "sports"},
2: {"name": "B", "grade": 12, "subject": "maths"},
3: {"name": "C", "grade": 8, "subject": "german"},
4: {"name": "D", "grade": 11, "subject": "maths"},
5: {"name": "E", "grade": 6, "subject": "art"},
6: {"name": "F", "grade": 9, "subject": "english"}
}
from collections import Counter
favorites = Counter(d["subject"] for _,d in student.items())
print(favorites)
Counter({'maths': 2, 'sports': 1, 'german': 1, 'art': 1, 'english': 1})
print(favorites.most_common(2))
[('maths', 2), ('sports', 1)]
可以通过创建一个包含每个主题在答案中出现的次数的默认字典来解决这个问题。然后使用max函数和lambda比较器来获取最受欢迎的主题,以保持简洁。
from collections import defaultdict
subject_count = defaultdict(lambda: 0)
for ind, student in students.items():
subject = student['subject']
subject_count[subject] += 1
print(max(subject_count.items(), key=lambda a: a[1]))