我需要创建一个名为stats的函数来返回列表列表,其中每个内部列表中的第一项是教师的名字,而教师所拥有的课程数中的第二项。 它应该返回:[[“Tom Smith”,6],[“Emma Li”,3]]
Argument是一个字典,如下所示:
teacher_dict = {'Tom Smith': ['a', 'b', 'c', 'd', 'e', 'f'], 'Emma Li': ['x', 'y', 'z']}
这是我的尝试:
def stats(teacher_dict):
big_list = []
for teacher, courses in teacher_dict.items():
number_of_courses = []
for key in teacher_dict:
teacher = ''
num = 0
for item in teacher_dict[key]:
num += 1
number_of_courses.append((key,num))
return big_list.append([teacher, number_of_courses])
另一次尝试:
def stats(teacher_dict):
big_list = []
for teacher in teacher_dict.items():
number_of_courses = len(teacher_dict[teacher])
return big_list.append([teacher, number_of_courses])
非常感谢任何帮助!这两个脚本都有错误,我在Python中仍然非常初级,但我真的想弄清楚这一点。 谢谢。
答案 0 :(得分:2)
使用列表理解
[[k, len(v)] for k, v in teacher_dict.items()]
答案 1 :(得分:0)
teacher_dict = {'Tom Smith': ['a', 'b', 'c', 'd', 'e', 'f'], 'Emma Li': ['x', 'y', 'z']}
stats = lambda teacher_dict: [[teacher, len(courses)] for teacher, courses in teacher_dict.items()]
stats(teacher_dict)
输出: [['Emma Li',3],['Tom Smith',6]]
答案 2 :(得分:0)
您的代码示例几乎是好的,问题是return
语句过早地结束了该函数。 append
调用也必须在循环内:
def stats(teacher_dict):
big_list = []
for teacher in teacher_dict.items():
number_of_courses = len(teacher_dict[teacher])
big_list.append([teacher, number_of_courses])
return big_list