繁体   English   中英

带有键的键字典

[英]Dictionary with Keys inside Keys

我需要找到一种方法来返回键1和2的键'hw'内的第一个值并将它们求和,但我想不出一种方法。它需要适用于任意数量的键,不仅是键1和2,甚至如果有10个左右。 1和2是学生,“ hw”,“ qz”等是作业的类别,每个学生都有hw,qz,ex,pr,每个学生都有3个qz,3hw,3pr,3ex学生。 我需要归还所有学生一年级,硬件年级,一年级测验年级,二年级硬件..etc

grades = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

更简洁(和Pythonicly):

hw_sum = sum([grades[key]['hw'][0] for key in grades])

返回键1和2的键“ hw”内的第一个值并将它们相加

使用解释性名称会有所帮助,因此我们知道运动部件的含义。 我通过猜测含义来任意选择了描述性名称。

简洁的解决方案

grades_by_year_and_subject = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

sum_of_grades_for_year_1_and_2_for_subject_hw = sum(
        grades[0] for grades in (
            grades_by_subject['hw']
            for (year, grades_by_subject) in
                grades_by_year_and_subject.items()
            if year in [1, 2]
            )
        )

将其分解为几个较小的问题:

汇总值的集合

sum_of_grades = sum(values)

从列表集合中获取第一组值

set_of_first_grades = {
        values[0] for values in collection}

生成集合中每个字典中键'hw'的值的生成器

generator_of_hw_value_lists = (
        values_dict['hw'] for values_dict in
        collection_of_dicts.values())

仅将字典简化为具有键12

mapping_of_values_for_key_1_and_2 = {
        key: value
        for (key, value) in values_dict.items()
        if key in [1, 2]}

详细解决方案

grades_by_year_and_subject = {
        1: {
            'pr': [18, 15],
            'hw': [16, 27, 25], 
            'qz': [8, 10, 5],
            'ex': [83, 93],
            },
        2: {
            'pr': [20, 18],
            'hw': [17, 23, 28],
            'qz': [9, 9, 8],
            'ex': [84, 98],
            },
        }

grades_for_year_1_and_2_by_subject = {
        year: grades_by_subject
        for (year, grades_by_subject) in
            grades_by_year_and_subject.items()
        if year in [1, 2]}

grades_for_year_1_and_2_for_subject_hw = (
        grades_by_subject['hw']
        for grades_by_subject in
            grades_for_year_1_and_2_by_subject.values())

sum_of_grades_for_year_1_and_2_for_subject_hw = sum(
        grades[0] for grades in grades_for_year_1_and_2_for_subject_hw)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM