【发布时间】:2016-02-10 22:31:33
【问题描述】:
所以我在 Treehouse 网站上的 Python 课程中间,问题正是这样问的:
创建一个名为 most_classes 的函数,该函数接受教师词典。每个键都是老师的名字,它们的值是他们教过的课程的列表。 most_classes 应该返回班级最多的老师。
在这里,我在下面发布了从 Treehouse 论坛上的资源中找到的正确代码,我也提出了同样的问题,但没有得到答复 - 那么分配教师 =“”到底是做什么的?我很困惑
# The dictionary will be something like:
# {'Jason Seifer': ['Ruby Foundations', 'Ruby on Rails Forms', 'Technology Foundations'],
# 'Kenneth Love': ['Python Basics', 'Python Collections']}
# Often, it's a good idea to hold onto a max_count variable.
# Update it when you find a teacher with more classes than
# the current count. Better hold onto the teacher name somewhere
# too!
def most_classes(my_dict):
count = 0
teacher = "" #this is where I am confused!
for key in my_dict:
if(len(my_dict[key]) > count):
count = len(my_dict[key])
teacher = key
return teacher
【问题讨论】:
-
teacher = ""将teacher绑定到一个空字符串。当my_dict为空时,这是一个很好的默认值(例如,循环永远不会迭代,也没有其他值被分配给teacher)。 -
似乎只为
max(my_dict, key=lambda x: len(my_dict[x]))做了很多工作。 -
@TigerhawkT3:你的意思是
max(my_dict, key=lambda x: len(my_dict[x]), default="")。 -
default在没有教师的情况下有效,但在字典中的教师没有班级的情况下无效。 -
@MartijnPieters,TigerhawkT3 你们处于另一个层次,我什至不明白你们发布的代码。 .大声笑。
标签: python variables python-3.x python-3.4