从JSON fi中的特定参数生成元素列表

2024-09-30 22:14:24 发布

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

我正在学校做一项作业,我被要求列出某一特定年份和类别的诺贝尔和平奖得主名单。 这是JSON文件的示例:

[{
        'year': '2018',
        'category': 'physics',
        'overallMotivation': '“for       groundbreaking inventions in the field of laser physics”',
        'laureates': [{
                'id': '960',
                'firstname': 'Arthur',
                'surname': 'Ashkin',
                'motivation': '"for the optical tweezers and their application to biological systems"',
                'share': '2'
            }, {
                'id': '961',
                'firstname': 'Gérard',
                'surname': 'Mourou',
                'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"',
                'share': '4'
            }, {
                'id': '962',
                'firstname': 'Donna',
                'surname': 'Strickland',
                'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"',
                'share': '4'
            }
        ]
    }, {
        'year': '2018',
        'category': 'chemistry',
        'laureates': [{
                'id': '963',
                'firstname': 'Frances H.',
                'surname': 'Arnold',
                'motivation': '"for the directed evolution of enzymes"',
                'share': '2'
            }, {
                'id': '964',
                'firstname': 'George P.',
                'surname': 'Smith',
                'motivation': '"for the phage display of peptides and antibodies"',
                'share': '4'
            }, {
                'id': '965',
                'firstname': 'Sir Gregory P.',
                'surname': 'Winter',
                'motivation': '"for the phage display of peptides and antibodies"',
                'share': '4'
            }
        ]
    }
]

我应该找到一种方法,找到谁赢得了一个特定的类别和年份的人的全名,这是我目前的代码

def get_laureates(dict_prizes, year = "none", category = "none"):


    names = []
    for row in dict_prizes: 
        if row["category"] == category:
            names.append(row["firstname"] + row['surname'])
    return names

year = 2018
category = "peace"

get_laureates(dict_prizes, year = 2018, category = "peace")

这就是输出

    TypeError                                 Traceback (most recent call last)
<ipython-input-168-57a2293c1bca> in <module>
         11 category = "peace"
         12 # test your function here
    ---> 13 get_laureates(dict_prizes, category = "peace")

    <ipython-input-168-57a2293c1bca> in get_laureates(dict_prizes, year,         category)
          4     names = []
          5     for row in dict_prizes:
    ----> 6         if row["category"] == category and row["year"] == year:
          7             names.append(row["firstname"] + row['surname'])
          8     return names

    TypeError: string indices must be integers

我知道这段代码中有很多错误,我无法将year转换成整数,即使去掉“years”参数,也无法仅用category生成结果。任何帮助都将不胜感激,因为我完全不懂JSON(给我的阅读材料只是教我如何转储和加载)。你知道吗


Tags: ofinidsharefornamessurnamefirstname
3条回答

在这里,我只是通过使用and来解决您的函数,并检查yearcategory是否与您提供的输入匹配。这样您就可以搜索属于该特定条件的所有值。此外,在检查条件时,year需要被视为字符串,因为它在json文件中是如何表达的。很明显,您可以删除仅用于验证目的的else:行。你知道吗

def get_laureates(category,year,json):  
    names = []
    for j in range(len(json)):
        if (json[j]['year'] == str(year)) and (json[j]['category'] == category):
            for i in range(len(json[j]['laureates'])):
                names.append(json[j]['laureates'][i]['firstname'] + ' ' + json[j]['laureates'][i]['surname'])
        else:
            print('Not found for category '+category+' and year '+str(year))
    return names
print(get_laureates(category='physics',year=2018,json=json))

输出:

Not found for category physics and year 2018
['Arthur Ashkin', 'Gérard Mourou', 'Donna Strickland']

超级一致性检查

您可以在定义函数后立即添加:

possibilities = ['physics','chemistry']
for i in range(len(possibilities)):
    print(get_laureates(category=possibilities[i],year=2018,json=json))

输出:

Not found for category physics and year 2018
['Arthur Ashkin', 'Gérard Mourou', 'Donna Strickland']
Not found for category chemistry and year 2018
['Frances H. Arnold', 'George P. Smith', 'Sir Gregory P. Winter']

你的代码通常是有效的,这意味着你的输入数据中有一些你没有在这里发布的东西丢失了。我无法用你给我们的数据重现你所看到的确切错误。你知道吗

有一个问题你没有考虑——你也需要循环遍历laureates,然后找出赢家,因为那也是一个字典列表。我是这样做的:

dict_prizes = [{'year': '2018', 'category': 'physics', 'overallMotivation': '“for       groundbreaking inventions in the field of laser physics”', 'laureates': [{'id': '960', 'firstname': 'Arthur', 'surname': 'Ashkin', 'motivation': '"for the optical tweezers and their application to biological systems"', 'share': '2'}, {'id': '961', 'firstname': 'Gérard', 'surname': 'Mourou', 'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"', 'share': '4'}, {'id': '962', 'firstname': 'Donna', 'surname': 'Strickland', 'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"', 'share': '4'}]}, {'year': '2018', 'category': 'chemistry', 'laureates': [{'id': '963', 'firstname': 'Frances H.', 'surname': 'Arnold', 'motivation': '"for the directed evolution of enzymes"', 'share': '2'}, {'id': '964', 'firstname': 'George P.', 'surname': 'Smith', 'motivation': '"for the phage display of peptides and antibodies"', 'share': '4'}, {'id': '965', 'firstname': 'Sir Gregory P.', 'surname': 'Winter', 'motivation': '"for the phage display of peptides and antibodies"', 'share': '4'}]}]

def get_laureates(dict_prizes, year = "none", category = "none"):
    names = []
    for row in dict_prizes: 
        if row["category"] == category:
            for winner in row['laureates']:   # You need this loop for the inner list of dictionaries
                names.append(winner['firstname'] + winner['surname'])
    return names

year = 2018
category = "physics"

get_laureates(dict_prizes=dict_prizes, year=2018, category=category)

得到:

>>> get_laureates(dict_prizes=dict_prizes, year=2018, category=category)
['ArthurAshkin', 'GérardMourou', 'DonnaStrickland']

既然你正在学习year,你也需要解决这个部分,因为你没有,所以我没有包括

对于提供的数据,您有一个JSON对象列表,每个对象包括

'year': type (string)
'category': type(string)
'overallMotivation': type(string)
'laureates' : type(list) - > this list comprises of more json objects

因为需要所有作者的名字和姓氏,所以需要遍历这两个列表。最初的一个首先匹配“年”和“类别”(要匹配您的年,请将年的数据类型更改为字符串),然后遍历“laureates”并继续附加row["firstname"] + row['surname']

def get_laureates(dict_prizes, year = None, category = None):
    names = []
    for category_wise_elements in dict_prizes:
        if category_wise_elements["category"] == category and 
           category_wise_elements['year'] == str(year):
            for winner in category_wise_elements['laureates']:
                names.append(winner["firstname"] + winner['surname'])
    return names

year = 2018
category = "peace"

get_laureates(dict_prizes, year = 2018, category = "peace")

我希望这对你有帮助

相关问题 更多 >