Python列表查重代码问题:为何查询提示不显示且newWord无法添加至列表?
问题分析与修正
咱们一步一步拆解你代码里的问题:
1. newWord 被赋值为 None,导致无法正常传递给查重函数
你写的 newWord = print(input('Enter a word: ')) 有个关键错误:print() 函数的返回值是 None。你输入的内容会被打印出来,但 newWord 实际拿到的是 None,而不是你输入的单词。所以当你把 newWord 传给 ifWordAlreadyExists 时,函数里的循环根本找不到匹配项,最后就把 None 加到列表里了。
正确的写法应该是直接获取输入值:
newWord = input('Enter a word: ')
2. 查询提示不显示 + 函数内部的语法错误
你的查重函数里有几个问题:
index = index(x):这里的index是列表的方法,需要通过myList.index(x)来调用,不然会报错(因为全局没有index()函数)。query = print(input('Word ', x ,'is already in index ', index , 'are you sure you want to include it? ')):input()只能接受一个字符串参数,不能用逗号分隔多个值,得用字符串拼接或者f-string来构造提示文本。- 同样,
print()套在外面会让query拿到None,应该直接用input()获取用户输入,不需要套print。
修正后的完整代码
myList = ["apple", "mango"] def ifWordAlreadyExists(word): for x in myList: if x == word: index = myList.index(x) # 用f-string构造提示文本,直接用input获取用户选择 query = input(f'Word {x} is already in index {index}, are you sure you want to include it? ') if query.lower() == 'y': return word else: return None # 如果单词不在列表里,直接返回原单词 return word newWord = input('Enter a word: ') result = ifWordAlreadyExists(newWord) # 只有result不是None的时候才添加到列表 if result is not None: myList.append(result) print(myList)
测试效果
当你输入apple时,会看到提示:
Enter a word: apple Word apple is already in index 0, are you sure you want to include it? y
此时列表会变成['apple', 'mango', 'apple'];如果输入n,则列表保持['apple', 'mango']。
内容的提问来源于stack exchange,提问作者user11520020
相关产品推荐
相关产品推荐

