我需要一个总和不同数字的代码

时间:2017-11-17 20:56:55

标签: python-2.7

我是一个非常困难的任务,因为我是python的新手,我希望你能够帮助我。 我写了这段代码:

def hours_per_student(student_course,course_hours):
    new={}
    for key in student_course.keys():
        for val in student_course.values():
               for m in range(len(val)):
                   if not new.has_key(key):
                        new[key]=course_hours[val[m]]
                   else: 
                        new[key]=new[key]+course_hours[val[m]]

    return new

这些词典:

student_course = {'rina' : ['math', 'python'], 'yossi' : ['chemistry', 'biology'], 'riki' : ['python']}
course_hours = {'math' : 4, 'python' : 4, 'chemistry' : 6, 'biology' : 5} 

我需要得到这个:

hours_per_student(student_course, course_hours) 

返回:

{'rina': 8, 'yossi': 11, 'riki': 4}  

但是我为每把钥匙保持相同的数字。

3 个答案:

答案 0 :(得分:2)

如果您已经在.values()进行迭代,则不应迭代.keys(),只需使用该键获取值即可。或者您有for m in len(val)的位置,只需for m in val然后引用m而不是val[m](这里的命名很糟糕,但我稍后再讨论)。迭代比Python要好得多。例如,而不是行

for val in student_course.values():

你应该尝试像

这样的东西
for courses in student_course[key]:
    for course in courses:
        if key not in new:
            new[key] = course_hours[course]
        else:
            new[key] += course_hours[course]

智能地命名变量将使您更容易跟踪正在发生的事情。例如,student_course中的每个值都是一个课程列表,因此您应该将其命名为val之类的含糊不清的内容。同样,courses中的每个元素都是课程的名称,因此请将其命名为。

答案 1 :(得分:1)

你走了:

solution = {student: sum([hours.get(course, 0) for course in s_courses]) for student, s_courses in student_course.items()}

答案 2 :(得分:0)

以下是我发现代码中缺少的内容:

  1. 在对学生进行迭代时,您可以为每个学生创建一个密钥,然后添加每个课程的小时数。

  2. 命名变量,以便您理解它们的含义是混淆的,不要使用newkeyval

  3. 您不必使用keys()函数,使用for key in dictionary迭代字典的方式相同。

  4. 这是一个固定的代码段:

    def hours_per_student(students, course_hours):
        total_hours = {}
        for student in students:
            courses = students[student]
            total_hours[student] = 0
            for course in courses:
                total_hours[student] += course_hours[course]
        return total_hours