如何检查单词是否存在于另一个函数返回的嵌套列表中?
问题解决:检查单词存在性失败的修复方案
问题根源
你的load_lexicon函数返回的是二维列表——比如文件里每行一个单词的话,返回结构是[['a'], ['b'], ...]。而check_word里用字符串(比如'a')直接判断是否在这个二维列表中,相当于比较'a' == ['a'],显然永远不匹配,所以无论输入什么都会返回“word not found”。另外函数里重复打开了两次文件,第一段with open的代码完全冗余,没有实际作用。
修复步骤
1. 修正load_lexicon函数
根据你的需求(存储单词列表),调整函数让它返回一维字符串列表:
- 如果
lexicon.txt是每行一个单词:
def load_lexicon(): liste_des_mots = [] with open("lexicon.txt", "r") as f: for ligne in f: mot = ligne.strip() # 跳过空行 if mot: liste_des_mots.append(mot) return liste_des_mots
- 如果
lexicon.txt是每行包含多个空格分隔的单词:
def load_lexicon(): liste_des_mots = [] with open("lexicon.txt", "r") as f: for ligne in f: mots = ligne.strip().split() # 把每行的单词逐个添加到总列表 liste_des_mots.extend(mots) return liste_des_mots
2. 优化check_word函数
同时建议只加载一次词典,避免每次查询都重复读取文件:
def check_word(): # 提前加载词典,减少IO操作 lexicon = load_lexicon() search_word = input("enter the word you want to search for: ").strip() if search_word in lexicon: print('word found') else: print('word not found')
额外优化建议
如果词典文件很大,用列表查询效率较低,可以改成集合存储,查询时间从O(n)降到O(1):
def load_lexicon(): mots_set = set() with open("lexicon.txt", "r") as f: for ligne in f: mot = ligne.strip() if mot: mots_set.add(mot) return mots_set
修改后check_word的判断逻辑无需改动,依然可以用search_word in lexicon,查询速度会明显提升。
内容的提问来源于stack exchange,提问作者Volew
相关产品推荐
相关产品推荐

