按值对字典列表进行排序 我一直在尝试使用lambda,但我无法弄清楚。
scale = {'A+': 4.3, 'A': 4.0, 'A-': 3.7,
'B+': 3.3, 'B': 3.0, 'B-': 2.7,
'C+': 2.3, 'C': 2.0, 'C-': 1.7,
'D+': 1.3, 'D': 1.0, 'D-': 0.7,
'F' : 0.0}
subject = {'math': {('Tom', 'B'), ('Kevin','D')},
'History': {('Kate', 'A+'),('Eric','C'),('Hannah','F')},
'English': {('Eli', 'B-')}}`
from collections import defaultdict
mingrade = 1.7
def pass(subject, mingrade):
output = defaultdict(list)
for subject_name,subject_grade in subject.items():
for student,grade in subject_grade:
if scale[grade]>=mingrade:
output[subject_name]+=[student]
return output
我得到了类似的输出 {'math':['Tom'],'History':{('Kate'),('Eric')},'English':{('Eli')} 但我想按名称和等级进行排序 'History':{('Kate'),('Eric')将变成'History':{('Eric'),('Kate')}按字母顺序排列。 我想按年级获得另一个。成绩较高的学生排名第一。
答案 0 :(得分:0)
好吧,为了获得两种不同类型的两种不同输出,我接受了您的代码,然后为函数创建了两种输出,其中一种按字母顺序排序,另一种按等级排序。
scale = {'A+': 4.3, 'A': 4.0, 'A-': 3.7,
'B+': 3.3, 'B': 3.0, 'B-': 2.7,
'C+': 2.3, 'C': 2.0, 'C-': 1.7,
'D+': 1.3, 'D': 1.0, 'D-': 0.7,
'F' : 0.0}
subject = {'math': {('Tom', 'B'), ('Kevin','D')},
'History': {('Kate', 'A+'),('Eric','C'),('Hannah','F')},
'English': {('Eli', 'B-')}}
from collections import defaultdict
mingrade = 1.7
def test(subject, mingrade):
alpha_sort = defaultdict(list)
grade_sort = defaultdict(list)
for subject_name,subject_grade in subject.items():
#here i sort the sets first alphabetically and then by grade
#the sorted function allows me to pass a function on which i want
#to sort them as with the key keyword
sort_alpha = sorted(subject_grade, key=lambda x: x[0].lower())
sort_grade = sorted(subject_grade, key=lambda x: scale[x[1]], reverse=True)
#now I loop over each sorted list as you did and store them in a
#seperate default dicts
for student,grade in sort_grade:
if scale[grade]>=mingrade:
grade_sort[subject_name]+=[student]
for student,grade in sort_alpha:
if scale[grade]>=mingrade:
alpha_sort[subject_name]+=[student]
return alpha_sort, grade_sort
alpha, grade = test(subject, mingrade)
print(alpha, grade)
给出此输出
defaultdict(<class 'list'>, {'math': ['Tom'], 'History': ['Eric', 'Kate'],
'English': ['Eli']})
defaultdict(<class 'list'>, {'math': ['Tom'], 'History': ['Kate', 'Eric'],
'English': ['Eli']})