2017-05-31 73 views
-3

列表索引範圍錯誤發生在該行列表索引超出範圍蟒蛇的3.6

if large_l[lg_index] ==small_l[sl_index]: 

這裏的時候,下面的值是代碼工作正常,

correctword = "syria" 
incorrectword = "siria" 

但分配值時如下,

correctword = "syria" 
incorrectword = "syri" 

上述錯誤已經發生。如果可以,告訴我一種擺脫這個錯誤的方法。 謝謝

correctword = "syria" 
incorrectword = "syri" 

l1 = list(correctword) 
l2 = list(incorrectword) 

if len(l1) < len(l2): 
    large_l= l2 
    small_l = l1 
else: 
    large_l =l1 
    small_l = l2 

missmatchstart = False 
lg_mismatch_start_index = 0 
sl_mismatch_start_index = 0 
lg_index = 0 
sl_index = 0 
del_count=0 
add_count = 0 
sub_count = 0 
for l1_item in large_l: 
    for l2_item in small_l: 
     if large_l[lg_index] ==small_l[sl_index]: 
      if missmatchstart == False: 
       sl_mismatch_start_index = sl_index 
       lg_mismatch_start_index = lg_index 
      print(large_l[lg_index]) 
      print("addition ") 
      print(add_count) 
      print("deletion ") 
      print(del_count) 
      print("substitution ") 
      print(sub_count) 
      if lg_index-lg_mismatch_start_index == sl_index-sl_mismatch_start_index: 
       sub_count += sl_index-sl_mismatch_start_index 
       lg_index+= 1 
       sl_index+= 1 
      elif lg_index-lg_mismatch_start_index > sl_index-sl_mismatch_start_index: 
       sub_count += sl_index-sl_mismatch_start_index 
       del_count += ((lg_index-lg_mismatch_start_index) - (sl_index-sl_mismatch_start_index)) 
       lg_index+= 1 
       sl_index+= 1 
      elif lg_index-lg_mismatch_start_index < sl_index-sl_mismatch_start_index: 
       sub_count += lg_index-lg_mismatch_start_index 
       add_count += ((sl_index-sl_mismatch_start_index) - (lg_index-lg_mismatch_start_index)) 
       lg_index+= 1 
       sl_index+= 1 
      missmatchstart = False 
      break 
     else: 
      print(large_l[lg_index]) 
      if(missmatchstart == False): 
       lg_mismatch_start_index = lg_index 
       sl_mismatch_start_index = sl_index 
       print("missmatch large") 
       print(lg_mismatch_start_index) 
       print("missmatch small") 
       print(sl_mismatch_start_index) 
       missmatchstart =True 
       sl_index+=1 
      else: 
       sl_index+=1 
      if sl_index== len(small_l)-1: 
       lg_index +=1 
       sl_index = sl_mismatch_start_index 
       #del_count +=1 
       break 
      # elif lg_index == sl_index == len(small_l): 
      #  sub_count += 

if lg_index >=len(large_l)-1: 
    del_count += len(large_l)- lg_index 
#elif missmatchstart ==True: 

print(add_count) 
print(del_count) 
print(sub_count) 

回答

1

你可能要替換線24的條件:

if large_l[lg_index] ==small_l[sl_index]: 

有:

if l1_item == l2_item: 

可能有其他錯誤出現,你應該讓你的代碼更通過將模塊分解爲多個功能(以合理的方式) - 它將更易於維護和調試!