正如在评论中提到一个set
会为了这个美好的,但由于分配约为名单,可以是这样的:
list_of_words = []
with open('romeo.txt') as f:
for line in f:
words = line.split()
for word in words:
if word not in list_of_words:
list_of_words.append(word)
sorted_list_of_words = sorted(list_of_words)
print(' '.join(sorted_list_of_words))
输出:
Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder
从用户请求的文件名的替代解决方案,采用继续并且是与Python 2.x的兼容:
fname = raw_input('Enter file: ')
wordlist = list()
for line in open(fname, 'r'):
words = line.split()
for word in words:
if word in wordlist: continue
wordlist.append(word)
wordlist.sort()
print ' '.join(wordlist)
输出:
Enter file: romeo.txt
Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder
通过使用加入摆脱[] ''。加入(LST)。此外,如果你想检查重复,你最好使用一套,而不是使用列表。 –