[英]Python list input 2 same words, how to print it only once
Hi first time posting here, I am trying to make a list that only prints an input once.嗨,第一次在这里发帖,我正在尝试制作一个仅打印一次输入的列表。 For example if the user enters: car dog dog house car then your program should display: car dog house
例如,如果用户输入:car dog dog house car 那么你的程序应该显示:car dog house
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)
I also tried我也试过
if word == wordlist:
wordlist[-1]
Any help would be great.任何帮助都会很棒。
If order of words does not matter use set
如果单词顺序无关紧要,请使用
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)
If order of insertion of word matters append the list with condition如果插入单词的顺序很重要,请附加带有条件的列表
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)
If you want to keep the duplicates but just want to remove while printing如果您想保留重复项但只想在打印时删除
for word in set(wordlist):
print(word)
If orders need to be maintained while printing如果在打印时需要维护订单
visited=set()
for word in wordlist:
if word not in visited:
print(word)
visited.add(word)
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
You can try following:您可以尝试以下操作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.