python - 根据 JSON 文件中的特定参数制作元素列表
问题描述
我正在为学校做作业,我被要求列出特定年份和类别的诺贝尔和平奖获得者的名单。这是 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
我知道这段代码中有很多错误,我无法将年份转换为整数,即使删除了“years”参数,我也无法仅使用类别生成结果。任何帮助都将不胜感激,因为我对 JSON 完全一无所知(给我的阅读材料实际上只是教会了我转储和加载)。
解决方案
在这里,我刚刚通过使用解决了您的功能,如果它检查两者year
并category
匹配您提供的输入。这样您就可以搜索属于该特定条件的所有值。此外,在检查条件时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']
推荐阅读
- testing - 使用 jest-dom 使用 Tailwind CSS 转换测试 React 组件的可见性
- mongodb - 如何将朋友的朋友添加到我的朋友列表中?
- google-colaboratory - 关于“在 Google colab 文本单元格中插入图片”的更多问题
- linux - 如何根据 .txt 文件 unix 中现有列的值添加新列
- javascript - JavaScript 如何解析查询
- java - 无法在测试单元中调用 JpaRepository
- javascript - 如何让codemirror处理双引号和单引号
- gitlab - 根据 Gitlab 中的前端或后端更改构建和部署
- azure - 如何使用 SQLAlchemy 连接到 Azure 服务器中的 MySQL
- parsing - 有没有办法在解析后使用关联性和优先级表来修复带有运算符的表达式?