You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决含字典嵌套列表的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:45:29