如何解决含字典嵌套列表的TypeError: list indices must be integers or slices, not str
问题分析与解决
错误原因
你的sentence是嵌套列表结构——外层列表的每一项都是包含单个字典的子列表,比如[{'entity': 'adj', ...}]。而你写的列表推导式直接遍历外层列表的元素(也就是这些子列表),试图用sub['entity']访问属性,这就触发了TypeError:列表只能用整数/切片索引,不能用字符串。
解决代码
方式1:嵌套列表推导式(一步完成)
直接遍历嵌套结构中的字典,同时过滤掉verb和prep类型的单词:
sentence = [[{'entity': 'adj', 'score': 0.9004535, 'index': 1, 'word': 'we', 'start': 0, 'end': 7}], [{'entity': 'verb', 'score': 0.8782018, 'index': 1, 'word': 'have', 'start': 0, 'end': 6}], [{'entity': 'verb', 'score': 0.9984743, 'index': 1, 'word': 'become', 'start': 0, 'end': 3}], [{'entity': 'noun', 'score': 0.9953852, 'index': 1, 'word': 'see', 'start': 0, 'end': 6}]] filtered_words = [word_dict['word'] for sub_list in sentence for word_dict in sub_list if word_dict['entity'] not in ('verb', 'prep')] print(filtered_words) # 输出: ['we', 'see']
方式2:先扁平化再筛选(更直观)
先把嵌套的列表结构展开成单层字典列表,再进行筛选:
# 第一步:展开嵌套列表 flattened_sentence = [item for sublist in sentence for item in sublist] # 第二步:过滤非verb/prep的单词 filtered_words = [item['word'] for item in flattened_sentence if item['entity'] not in ('verb', 'prep')] print(filtered_words) # 输出: ['we', 'see']
内容的提问来源于stack exchange,提问作者Mhmd Rokaimi
相关产品推荐
相关产品推荐

