Python:同一个单词在列表中出现两次



我正在尝试编写一个程序,如果给出相同的单词两次,则停止。这段代码几乎是工作,但它停止只有在重复的单词按顺序给出。谢谢你的帮助。

list = []
double = None
while True:
word = input("word: ")
lista.append(word)
if douple == word:
print(f"You gave {len(list)} words")
break
double = word

您需要检查该单词是否已经在列表中

seen = []
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.append(word)

如果你只是想告诉重复的,并且不需要保持顺序,你可以使用set代替;对于大量的单词,这将更有效:

seen = set()
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen.add(word)

最后,在最近的Python(至少3.6或3.7,取决于你如何理解)中,你可以通过使用字典来实现这两个目标;这既有效又保持了输入单词的顺序:

seen = {}
while True:
word = input("word: ")
if word in seen:
print(f"You gave {len(seen)} words")
break
seen[word] = None

将代码修改为如下所示:

words_list = []
while True:
word = input("Word: ")
if word not in words_list:    #Checks if the word is in the list. If it exists in list, it would return False
words_list.append(word)
else:
print(f"You gave {len(words_list)} words")
break

我已经改变了一些东西:

  1. 不要使用list作为变量名,因为它是Python中的关键字。
  2. 在将其添加到列表之前,使用not in检查是否有重复的单词。如果word在列表中存在,循环将中断。

这个应该可以完成工作。如果你需要澄清或者代码不能正常工作,你可以随时注释。