我尝试在特定键处添加列表,但字典中的列表为空

2024-04-19 05:10:51 发布

您现在位置:Python中文网/ 问答频道 /正文

for student_id in range(1,len(student)+1):
    for test_id in range(len(marks)):
        if marks["student_id"][test_id] == student_id:
            test_list.append(marks["test_id"][test_id])
    
    test_dict[student_id] = [test_list]
    test_list.clear()

print(test_dict)

在将列表添加到字典之前,我做了一些测试,列表中包含一些结果,但在字典中它是空的。当我在网上搜索时,一切看起来都很正常


1条回答
网友
1楼 · 发布于 2024-04-19 05:10:51

更像Python的方式是这样的:

for student_id in range(1,len(student)+1):
    
    # make a new list for every iteration
    test_list = []
    
    for test_id in range(len(marks)):
        if marks["student_id"][test_id] == student_id:
            test_list.append(marks["test_id"][test_id])
    
    test_dict[student_id] = test_list # no additional []
    # no .clear()

print(test_dict)

相关问题 更多 >