2017-01-20 2 views
-2

파이썬의 목록에있는 단어의 색인을 인쇄하는 방법을 찾으려고합니다.목록의 색인 Python

sentence = input("Enter").lower() 
words = sentence.split() 
counts = [] 
for word in words: 
    if word not in counts: 
     counts.append(word) 
print(counts) 
: 문장 나는 그것이

내가 이것으로 모든 단어 중복 제거 목록 "1, 2, 2, 1, 3")를 인쇄 할) "안녕하세요 세계 세계 안녕하세요 이름"인 경우

하지만 인덱스가 "나는 문장에서 볼 수 n 번째의 고유 단어"싶은 경우에 여전히 배열

+4

시도해 보셨습니까? –

+0

가능한 [Python으로 열린 파일을 작성할 때 분할 기능]의 복제본 (http://stackoverflow.com/questions/41726645/split-function-when-writing-an-opened-file-in-python) –

+1

원하는대로 그 목록은 단어의 첫 출현에 대한 색인의 목록이 될 것인가? 제발 [ask]를보세요 – Sayse

답변

0

를 사용하여 문장의 인덱스를 얻을 필요가 다음이 코드는 다음을 생산하는 것입니다 :

sentence = "Hello world world hello name".lower() 
first_occurence = dict() 
for pos, word in enumerate(sentence.split(" ")): 
    if word not in first_occurence: 
     first_occurence[word] = len(first_occurence) 

res = [first_occurence[word] + 1 for word in sentence.split(' ')] 

결과 : [1, 2, 2, 1, 3]