【问题标题】:Function to create a list of lists创建列表列表的函数
【发布时间】:2017-01-03 19:07:11
【问题描述】:

我需要创建一个名为 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 方面还很初级,但真的很想弄清楚这一点。 谢谢你。

【问题讨论】:

  • 请详细说明您尝试解决此问题时遇到的问题。
  • 是的,也坚持一种实现,我建议尝试编写一些代码来测试您的方法并打印输出,以便我们可以复制和粘贴您的代码。我们要做的苦差事越少,社区就越乐于助人。

标签: python function python-3.x collections


【解决方案1】:

使用列表推导

[[k, len(v)] for k, v in teacher_dict.items()]

【讨论】:

  • 我一直很欣赏单行、干净、简单的解决方案。 IMO,这是初学者最容易理解的。
  • 这看起来很简单!不敢相信,谢谢帕特里克。你能解释一下你为什么使用 .items() 方法吗?
  • @MaiiaS。 items 提供了字典的视图,您基本上可以将其视为像 [('Tom Smith', ['a', 'b', 'c']), ...] 这样的元组列表,其中元组的第一个元素是它们在字典中的键,第二个元素是键值。当您直接遍历字典 for x in d 时,您实际上只是在遍历键。
【解决方案2】:
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)

输出: [['艾玛李',3],['汤姆史密斯',6]]

【讨论】:

    【解决方案3】:

    您的代码示例几乎可以使用,问题是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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多