如何在字典的元组中获取值?

时间:2019-04-10 00:46:00

标签: python dictionary

我想使用lambda函数访问字典中的元组中的值

我需要通过比较该班学生的平均成绩来获得每个学科的平均GPA

我尝试使用lambda,但无法弄清楚。

const arr = [1,1,2,3,3,3,3,4,5,5,10];

var
  counting  = {},
  most_Freq = arr[0]
  ;

arr.forEach( x=>{ counting[x] = (counting[x] || 0)+1; });

most_Freq = Object.keys(counting).reduce((a, b) => counting[a] > counting[b] ? a : b);

console.log ( 'most frequent is ', most_Freq )

输出必须为 grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0} subjects = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}} def highestAverageOfSubjects(subjects): return ,因为数学的平均GPA为3.0大于英语2.0的平均GPA

2 个答案:

答案 0 :(得分:1)

通过将sortedkey函数一起使用,您可以轻松地对所有内容进行排序:

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
result = sorted(subject, key=lambda x: sum(Grade[g] for _, g in subject[x]) / len(subject[x]), reverse=True)
print(result)

输出:

['math','English']

如果作为中学,您想要按学生人数排序:

result = sorted(subject, key=lambda x: (sum(Grade[g] for _, g in subject[x]) / len(subject[x]), len(subject[x])), reverse=True)
print(result)

答案 1 :(得分:0)

实现方式的问题之一是您在set字典中使用了subject作为值。这意味着您必须覆盖每个元素。但是一旦有了元素,该值将像elem[1]一样被索引。

例如:

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
for elem in subject['math']:
    print(elem[1])

输出:

C
A

如果在上方的print中,您print(elem)会出现类似的内容:

('Larry', 'C')
('Jack', 'A')

因此,您可以轻松地扩展highAveSub(subject)实现以获取所需的内容。

要查找某个主题的平均成绩:

def highAveSub(subname):
    total = 0
    for elem in subject[subname]:   #Because your values are of type set, not dict.
        total = total + grade[elem[1]]    #This is how you will cross-reference the numerical value of the grade. You could also simply use enums and I'll leave that to you to find out
    avg = total / len(subject[subname])
    return avg
相关问题