
本文介绍如何解决python中`list.index()`仅返回首次匹配索引导致无法区分同一单词多个出现位置的问题,并提供基于`enumerate`和字典映射的健壮解决方案。
在Python中,list.index(value)方法始终返回该值第一次出现的索引,而非当前遍历位置——这正是原代码失效的根本原因。例如,对列表 ["hello", "hello", "world", "hello"],无论你在循环中访问哪个 "hello",x.index("hello") 永远返回 0。因此,嵌套循环中 x.index(i) != x.index(j) 在 i == j 时恒为 False,导致无输出。
要真正区分同一单词的不同出现位置,必须脱离对 .index() 的依赖,转而记录每个单词在原始序列中的实际下标。推荐使用 enumerate() 配合字典累积索引:
s = "The hello hello substring string of this pan is amazing hello"
words = s.split()
# 构建 {单词: [所有出现索引列表]} 的映射
word_positions = {}
for idx, word in enumerate(words):
if word not in word_positions:
word_positions[word] = []
word_positions[word].append(idx)
# 输出所有出现次数 ≥2 的单词及其全部索引(按题意格式)
for word, indices in word_positions.items():
if len(indices) > 1:
# 格式:hello,1,hello,2,hello,10
parts = [f"{word},{i}" for i in indices]
print(",".join(parts))✅ 关键优势: enumerate() 提供真实、不可变的位置信息(从0开始递增),完全规避 .index() 的“首次匹配陷阱”; 字典值为列表,天然支持多索引存储; 时间复杂度 O(n),远优于嵌套循环+重复调用 .index() 的 O(n²)。
⚠️ 注意事项:
- 原问题中 input= 覆盖了内置函数 input,应避免使用 input 作为变量名;
- 若需区分大小写或处理标点,建议先统一小写并清理非字母字符(如 re.sub(r'[^\w\s]', '', s).lower().split());
- 此方案天然支持任意重复次数的单词,不限于两次。
该方法不仅解决了当前问题,更是处理“词频+位置分析”类任务的标准范式,适用于文本去重、关键词高亮、语义距离计算等场景。
立即学习“Python免费学习笔记(深入)”;










