我正在学校做一项作业,我被要求列出某一特定年份和类别的诺贝尔和平奖得主名单。 这是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(给我的阅读材料只是教我如何转储和加载)。你知道吗
在这里,我只是通过使用and来解决您的函数,并检查
year
和category
是否与您提供的输入匹配。这样您就可以搜索属于该特定条件的所有值。此外,在检查条件时,year
需要被视为字符串,因为它在json文件中是如何表达的。很明显,您可以删除仅用于验证目的的else:
行。你知道吗输出:
超级一致性检查
您可以在定义函数后立即添加:
输出:
你的代码通常是有效的,这意味着你的输入数据中有一些你没有在这里发布的东西丢失了。我无法用你给我们的数据重现你所看到的确切错误。你知道吗
有一个问题你没有考虑——你也需要循环遍历
laureates
,然后找出赢家,因为那也是一个字典列表。我是这样做的:得到:
既然你正在学习
year
,你也需要解决这个部分,因为你没有,所以我没有包括对于提供的数据,您有一个JSON对象列表,每个对象包括
因为需要所有作者的名字和姓氏,所以需要遍历这两个列表。最初的一个首先匹配“年”和“类别”(要匹配您的年,请将年的数据类型更改为字符串),然后遍历“laureates”并继续附加
row["firstname"] + row['surname']
我希望这对你有帮助
相关问题 更多 >
编程相关推荐