我该如何解决这个错误?类型错误:列表索引必须是整数或切片,而不是 str

时间:2021-01-20 14:02:20

标签: 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',
   '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

1 个答案:

答案 0 :(得分:1)

您必须在开头定义 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']}