正如在評論中提到一個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)。此外,如果你想檢查重複,你最好使用一套,而不是使用列表。 –