how I can fix this error? TypeError: list indices must be integers or slices, not str

橙三吉。 提交于 2021-01-29 03:57:23

问题


I have a list like this:

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

I want to run the following code:

categories=set(x['result']['categoryName'] for x in mylist)

It gives me the error:

TypeError: list indices must be integers or slices, not str


回答1:


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

Regarding the question in the comment below: to make that code work, define the variables before using them, and add another if condition:

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


来源:https://stackoverflow.com/questions/65811068/how-i-can-fix-this-error-typeerror-list-indices-must-be-integers-or-slices-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!