Python列表输入2个相同的单词,如何只打印一次

时间:2019-01-24 22:16:10

标签: python list

您好,第一次在这里发帖,我试图制作一个仅打印输入一次的列表。例如,如果用户输入: 汽车 狗 狗 屋 汽车 然后您的程序应显示: 汽车 狗 房子

wordlist = []
while True:
  word  = (input("Enter a word (blank to quit): "))
  wordlist.append(word)
  if word == wordlist:
   wordlist.remove(word)
  if word == "":
     break

for word in wordlist:
    print(word)

我也尝试过

if word == wordlist:
    wordlist[-1]

任何帮助都会很棒。

3 个答案:

答案 0 :(得分:1)

如果单词顺序无关紧要,请使用set

wordlist = set()
while True:
    word  = (input("Enter a word (blank to quit): "))
    if word == "":
        break
    wordlist.add(word)

for word in wordlist:
    print(word)

如果单词的插入顺序很重要,请在列表后面加上条件

wordlist = []
while True:
    word  = (input("Enter a word (blank to quit): "))
    if word == "":
        break
    if word not in wordlist:
        wordlist.append(word)

for word in wordlist:
    print(word)

如果您想保留重复项,而只想在打印时将其删除

for word in set(wordlist):
    print(word)

如果在打印时需要维护订单

visited=set()
for word in wordlist:
    if word not in visited:
        print(word)
        visited.add(word)

答案 1 :(得分:0)

In [49]: words = 'car dog dog house car'.split()                                           

In [50]: from collections import OrderedDict                                               

In [51]: word_dict = OrderedDict()                                                         

In [52]: for word in words: 
    ...:     word_dict[word] = None 
    ...:                                                                                   

In [53]: for word in word_dict: 
    ...:     print(word) 
    ...:                                                                                   
car
dog
house

答案 2 :(得分:0)

您可以尝试以下操作:

wordlist = []
while True:
  word  = (input("Enter a word (blank to quit): "))
  if not word:
    break
  elif word not in wordlist:
    wordlist.append(word)

for word in wordlist:
    print(word)