我有一个这样的列表:
mylist[1:3]=[{'Keywords': 'scrum master',
'result': {'categoryId': '3193',
'categoryName': 'agile coach',
'score': '1.0'},
'categoryId': '3193'},
{'Keywords': 'principal consultant',
'result': {'categoryId': '2655',
'categoryName': 'principal consultant',
'score': '1.045369052886963'},
'categoryId': '2655'},
{'Keywords': 'technicalfunctional consultant',
'result': []}]
我想运行以下代码:
categories=set(x['result']['categoryName'] for x in mylist)
它给出了错误:
TypeError: list indices must be integers or slices, not str
您必须在开始定义mylist
,并为其元素添加if
测试,然后代码工作:
mylist = []
mylist[1:3]=[{'Keywords': 'scrum master',
'result': {'categoryId': '3193',
'categoryName': 'agile coach',
'score': '1.0'},
'categoryId': '3193'},
{'Keywords': 'principal consultant',
'result': {'categoryId': '2655',
'categoryName': 'principal consultant',
'score': '1.045369052886963'},
'categoryId': '2655'},
{'Keywords': 'technicalfunctional consultant',
'result': []}]
categories = set(x['result']['categoryName'] for x in mylist
if x['result'] and 'categoryName' in x['result'])
print(categories)
# {'agile coach', 'principal consultant'}
关于下面评论中的问题:为了使代码工作,在使用变量之前定义它们,并添加另一个if
条件:
cat_dict = {}
cat_set = set(['agile coach', 'principal consultant'])
for cat_name in cat_set:
cat_dict[cat_name] = [elem["Keywords"] for elem in mylist
if elem["result"] and elem["result"]["categoryName"] == cat_name]
print(cat_dict)
# {'agile coach': ['scrum master'], 'principal consultant': ['principal consultant']}