从字典值创建列表列表

2024-09-30 12:22:35 发布

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

我需要按月筛选这些数据。我需要的结果是一个列表的列表,如 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]

如何使结果成为一个列表列表

埃塔。我需要在几周内学会如何在没有准备好考试的外部库的情况下做这些事情


Tags: 数据in列表fordatadatetypejohn
2条回答

你可能会有更好的时间每月将分数汇总成一份dict,然后如果你需要一份包含所有月份的列表,不管他们是否有分数,这很容易:

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]}。)

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]、[]、[]、[]、[]、[]、[]、[]、[]、[]、[]、[]、[]、[]、[]]

相关问题 更多 >

    热门问题