从字典值创建列表列表

时间:2021-05-14 08:56:00

标签: python list dictionary

我需要按月过滤此数据。我需要结果是一个像列表一样的列表 lst = [[92], [86], [89]]

这是我尝试过的:

data_dict = [
    {
        "student": "john",
        "subject": "english",
        "grade": "A",
        "marks": 92,
        "assessement type": "exam",
        "date": [2, 1, 2021],
    },
    {
        "student": "john",
        "subject": "math",
        "grade": "B",
        "marks": 86,
        "assessement type": "essay",
        "date": [2, 3, 2021],
    },
    {
        "student": "john",
        "subject": "history",
        "grade": "B",
        "marks": 89,
        "assessement type": "presentation",
        "date": [22, 2, 2021],
    },
]

lst = []
for x in data_dict:
    for i in range(1, 13):
        if x["date"][1] == i:
            lst.append(x["marks"])

输出:

lst = [92, 86, 89]

如何使结果成为列表列表?

预计到达时间。我需要学习如何在没有准备好几周后考试的外部图书馆的情况下做这些事情。

2 个答案:

答案 0 :(得分:1)

您可能有更好的时间将每个月的成绩汇总到一个字典中,然后如果您需要一个包含所有月份的列表,无论它们是否有成绩,这都很容易:

from collections import defaultdict

data_dict = [
    {
        "student": "john",
        "subject": "english",
        "grade": "A",
        "marks": 92,
        "assessement type": "exam",
        "date": [2, 1, 2021],
    },
    {
        "student": "john",
        "subject": "math",
        "grade": "B",
        "marks": 86,
        "assessement type": "essay",
        "date": [2, 3, 2021],
    },
    {
        "student": "john",
        "subject": "history",
        "grade": "B",
        "marks": 89,
        "assessement type": "presentation",
        "date": [22, 2, 2021],
    },
]

grades_by_month = defaultdict(list)

for x in data_dict:
    grades_by_month[x["date"][1]].append(x["marks"])

grades_every_month = [grades_by_month[x] for x in range(1, 13)]
print(grades_every_month)

打印出来

[[92], [89], [86], [], [], [], [], [], [], [], [], []

grades_by_month 看起来像 {1: [92], 3: [86], 2: [89]}。)

答案 1 :(得分:0)

lst = []
for i in range(1,13):
    templst = []
    for x in data_dict:
        if x["date"][1]==i:
            templst.append(x["marks"])
    lst.append(templst) 


lst

输出:[[92, 93, 89], [89], [86], [], [], [], [], [], [], [], [], []]< /p>

相关问题