【问题标题】:how I can fix this error? TypeError: list indices must be integers or slices, not str我该如何解决这个错误? TypeError:列表索引必须是整数或切片,而不是 str
【发布时间】:2021-04-24 21:47:35
【问题描述】:

我有一个这样的列表:

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

【问题讨论】:

    标签: python list dictionary set


    【解决方案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']}
    

    【讨论】:

    • 我认为问题在于categoryName 的某些部分是空的。我该如何解决?
    • @Nagh 请使用minimal reproducible example 编辑问题,以便我们重现该行为。谢谢。
    • 非常感谢。我工作了好几个小时。这个怎么样:for cat_name in cat_set: cat_dict[cat_name] = [elem["Keywords"] for elem in normalization_list if elem["result"]["categoryName"] == cat_name]
    • @Nagh 我认为如果您将下一个问题作为单独(新)问题发布,您会得到更好的答案。它将吸引更多的用户和更好的答案。祝你好运!
    • 我现在不能问更多问题。因为我问了 6。如果可以的话,你能帮帮我吗?我真的需要帮助
    猜你喜欢
    • 1970-01-01
    • 2015-12-09
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多