我该如何解决此错误?TypeError:列表索引必须是整数或切片,而不是str [英] how I can fix this error? TypeError: list indices must be integers or slices, not str
本文介绍了我该如何解决此错误?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:列表索引必须是整数或切片,而不是str
推荐答案
您必须在开始时定义 mylist
,并为其元素添加 if
测试,然后该代码有效:
You have to define mylist
at the beginning, and add an if
test for its elements, then the code works:
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']}
这篇关于我该如何解决此错误?TypeError:列表索引必须是整数或切片,而不是str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文