2017-12-28 5 views
1

Ich mache ein Programm zum Entfernen doppelter Wörter in einer Liste in Python mit der split() Funktion.Entfernen von Duplikaten in einer Liste

Meine Antwort ist falsch, da die doppelten Elemente nicht entfernt werden.

romeo.txt:

But soft what light through yonder window breaks 
It is the east and Juliet is the sun 
Arise fair sun and kill the envious moon 
Who is already sick and pale with grief 

Mein Code:

fhand=open(romeo.txt) 
arr=list() 
count=0 
for line in fhand: 
    words=line.split() 
    if words in arr: 
     continue 
    else: 
     arr=arr+words 

arr.sort() 
print(arr) 

Antwort

1
  1. Sie müssen über jedes Wort wiederholen, nicht jede Zeile.
  2. Verwenden Sie append(), um Wörter zu einer Liste hinzuzufügen.

Beispiel:

line="But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief" 

arr=list() 
count=0 

words=line.split() 
for word in words: 
    if word not in arr: 
     arr.append(word) 

arr.sort() 
print(arr) 

Output:

['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'] 
Verwandte Themen