Python 如何修复此错误?TypeError:列表索引必须是整数或片,而不是str
我有这样一份清单:Python 如何修复此错误?TypeError:列表索引必须是整数或片,而不是str,python,list,dictionary,set,Python,List,Dictionary,Set,我有这样一份清单: mylist[1:3]=[{'Keywords': 'scrum master', 'result': {'categoryId': '3193', 'categoryName': 'agile coach', 'score': '1.0'}, 'categoryId': '3193'}, {'Keywords': 'principal consultant', 'result': {'categoryId': '2655', 'categor
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
,并添加如果对其元素进行测试,则代码工作:
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']}
我认为问题在于,categoryName
中的一些是空的。我该如何修复它?@Nagh请用编辑问题,以便我们可以重现该行为。谢谢。请看编辑,thanks@Nagh请看最新的答案。非常感谢。我花了好几个小时在工作。这个怎么样:对于cat\u集合中的cat\u名称:cat\u dict[cat\u name]=[elem[“Keywords”]对于规范化列表中的elem,如果elem[“result”][“categoryName”]==cat\u name]