2017-12-28 11 views
1

split() 함수를 사용하여 파이썬의 목록에서 중복 단어를 제거하는 프로그램을 수행하고 있습니다.목록에서 중복을 제거합니다.

중복 요소가 제거되지 않으므로 내 대답은 잘못되었습니다.

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 

내 코드 :

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) 
당신은 각 단어를 반복 할 필요가

답변

1
  1. , 하지 각 라인.
  2. append()을 사용하여 단어를 목록에 추가하십시오.

예 :

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) 

출력 :

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