2017-04-20 1 views
0

여기에서 내가 처음으로 물어 본 것은 이번이 처음입니다. 최선을 다할 것입니다. 나는이 가지고문자열 목록에서 요소를 모두 제거합니다.

array2 = ["A very long string saying some things", 
      "something different", 
      "this is a test"]` 

: :이 결과를 원하는

array = ["A very long string saying some things", 
     "Another long string saying some things", 
     "extremely large string saying some things", 
     "something different", 
     "this is a test"] 

: 나는처럼, 모두 모든 문구를 제거하려면, 문구와 목록이

for i in range(len(array)): 
    swich=True 
    for j in range(len(array2)): 
     if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == True): 
      swich=False 
      pass 
     if (fuzz.ratio(array[i],array2[j]) >= 80) and (swich == False): 
      array2.pop(j) 

그러나 그것을 나에게 목록을 준다 IndexError ...

fuzzy.ratio는 두 개의 문자열을 비교하여 값을 준다. 트윈 0과 100, 큰, 더 똑같이 문자열이 있습니다.

엘리먼트별로리스트를 비교하려고합니다. 두 개의 유사한 문자열을 처음 발견했을 때, 스위치를 켜고 그 점을 모두 통과하면, array2 요소가 나타납니다. 나는 어떤 제안이라도 완전히 열어 둔다.

+2

정확한 오류 추적을 제공하십시오 ... 목록에 색인 오류가 있습니까? – rassar

답변

0

오류는 그 시점에서 반복되는 목록 수정으로 인해 발생합니다. (현재 반복되는 iterable 요소를 추가/제거/대체하지 마십시오!) range(len(array2))은 길이가 N임을 알고 있지만 array2.pop(j) 이후 길이는 더 이상 N이 아니지만 N-1입니다. 나중에 N 번째 요소에 액세스하려고하면 목록이 더 짧아 졌으므로 IndexError이 표시됩니다.

다른 접근 방식에 빠른 추측 :

original = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"] 

filtered = list() 

for original_string in original: 
    include = True 
    for filtered_string in filtered: 
     if fuzz.ratio(original_string, filtered_string) >= 80: 
      include = False 
      break 
    if include: 
     filtered.append(original_string) 

더 "파이썬"이고 어떤 정수 변수도 범위를 필요로하지 않는다 for string in array 루프, 유의하시기 바랍니다.

0

코드를 압축하고 루프 수를 줄이는 다른 라이브러리를 사용하는 것은 어떻습니까?

import difflib 

def remove_similar_words(word_list): 
    for elem in word_list: 
     first_pass = difflib.get_close_matches(elem, word_list) 
     if len(first_pass) > 1: 
      word_list.remove(first_pass[-1]) 
      remove_similar_words(word_list) 
    return word_list 


l = ["A very long string saying some things", "Another long string saying some things", "extremely large string saying some things", "something different", "this is a test"] 

remove_similar_words(l) 

['A very long string saying some things', 
'something different', 
'this is a test'] 
관련 문제