簡體   English   中英

創建列表列表的功能

[英]Function to create a list of lists

我需要創建一個名為stats的函數以返回列表列表,其中每個內部列表中的第一項是老師的姓名,第二項是老師所擁有課程的數量。 它應該返回:[[“ Tom Smith”,6],[“ Emma Li”,3]]

參數是一個字典,看起來像:

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還是很初級,但是真的想弄清楚這一點。 謝謝。

使用列表理解

[[k, len(v)] for k, v in teacher_dict.items()]
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]]

您的代碼示例幾乎可以執行,問題是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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM