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

2024-05-18 12:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一份清单:

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


Tags: 代码masterprincipalresultcategoriesscorescrumkeywords
1条回答
网友
1楼 · 发布于 2024-05-18 12:34:16

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

相关问题 更多 >

    热门问题