2013-04-11 2 views
2

논리적 인 오류가 발생했습니다.이를 선택하지 못했습니다.Python : 추가 문제 나열

Document = 'Sample1' 
locationslist = [] 
thedictionary = [] 
userword = ['the', 'a'] 
filename = 'Sample1' 
for inneritem in userword: 
    thedictionary.append((inneritem,locationslist)) 
    for position, item in enumerate(file_contents): 
     if item == inneritem: 
      locationslist.append(position) 
wordlist = (thedictionary, Document) 
print wordlist 

을 그래서 기본적으로 내가 함께 특정 userword와 작은 목록 (locationslist)에서 큰 목록 (thedictionary)를 만들려고 오전 : 여기에 내가 가진 것입니다. 나는 출력이 각 단어의 모든 위치 (단지 2 - 'the''a')를 각 목록에 두는 것을 제외하고는 거의 가지고있다. 간단한 논리 문제가있는 것처럼 보입니다. 그러나 나는 그것을 발견 할 수 없습니다.

([('the', [5, 28, 41, 97, 107, 113, 120, 138, 141, 161, 2, 49, 57, 131, 167, 189, 194, 207, 215, 224]), 
    ('a', [5, 28, 41, 97, 107, 113, 120, 138, 141, 161, 2, 49, 57, 131, 167, 189, 194, 207, 215, 224])], 
'Sample1') 

그러나해야합니다 : 출력은

([('the', [5, 28, 41, 97, 107, 113, 120, 138, 141, 161]), 
    ('a', [2, 49, 57, 131, 167, 189, 194, 207, 215, 224])], 
'Sample1') 

두 위치 목록이 userwords 'the''a'의 각 관한 문제 출력의 각에 추가되는 방법을 참조하십시오? 내가 여기서 잘못하고있는 것에 대한 조언을 사용할 수 있습니다.

답변

3

locationslist 만 만들 수 있으므로 하나만 만들면됩니다. 두 단어가 공유합니다. 각 루프 반복에 대한 새로운 locationslist을 만들어야합니다

for inneritem in userword: 
    locationslist = [] 
    thedictionary.append((inneritem,locationslist)) 
    # etc. 
+0

고마워요. BrenBarn .. 가끔은 당신이 스스로 말뚝 드라이버를주고 싶어하는 보이지 않는 작은 수정입니다. – Relative0

1

당신은 단지 하나의 locationslist를 만든, 그래서 모든 locationslist.append() 통화의 목록을 수정합니다. thedictionary에있는 튜플의 수와 동일한 locationslist을 추가하면 userword의 요소가 있습니다. userword의 각 요소에 대해 하나의 위치 목록을 만들어야합니다.

올바른 목록으로 이어질 것입니다 당신이 지능형리스트의 중첩 세트로 기록 될 수있는 알고리즘은, 생성되는

: 아직 어떤 수, user_word의 각 항목에 대해 한 번 enumerate(file_contents)을 부를 것이다

user_word = ['the', 'a'] 
word_list = ([(uw, 
       [position for position, item in enumerate(file_contents) 
       if item == uw]) 
       for uw in user_word], 
      'Sample1') 

file_contents이 큰 경우 비용이 많이 든다.

file_contents을 한 번만 넘겨주고 user_word의 내용에 대해 각 위치의 항목을 확인한 다음 그 위치에있는 특정 user_word의 목록에만 위치를 추가하십시오. 나는 접근 목록을 분리 user_word하고 유지하는 사전을 사용하는 것이 좋습니다 것입니다 :

document = 'Sample1' 

temp_dict = dict((uw, []) for uw in user_word) 

for position, item in enumerate(file_contents): 

if item in temp_dict: 
    temp_dict[item].append(position) 

wordlist = ([(uw, temp_dict[uw]) for uw in user_word], document) 

어느 솔루션은 문서 스캔에, 외관의 순서로 당신에게 각 user_word의 위치를 ​​얻을 것이다. 또한 원하는 목록 구조를 반환합니다.

+0

감사합니다. – Relative0