我如何修复这个错误?TypeError:列表索引必须是整数或切片,而不是str



我有一个这样的列表:

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']}

相关内容

  • 没有找到相关文章