2014-11-24 49 views
0

我通過字典迭代,如果某些條件匹配,則刪除字典項目。現在字典動態索引得到更新。在刪除項目後堅持字典索引

例如

{u'Titanic': {'match': [{'category': u'Book'}, 
         {'category': u'Movie'}, 
         {'category': u'Product'}], 
       'score': 100}} 

雖然迭代match,如果我刪除Book(指數 - 0),所以現在下一個迭代過程中它顯示我product(指數 - 1)直接,考慮到指數0 movie。它考慮已經迭代的索引-0。

代碼剪斷:

for k1,v1 in enumerate(value['match']): 
     if k1 != '': 
      print '\n Category: ',k1,' ',v1['category'] 

      print 'Do you want to change the class of entity',k1 ,'? Y/N', 'Or delete', k1, '1/0' 
      choice = raw_input() 
      if choice == 'N' or choice == 'n': 
       pass 
      elif choice == 'Y' or choice == 'y' : 
       print '\tEnter class : \t' 
       v1['category'] = raw_input() 
       tagged = string.replace(sentence, key, v1['category']) 
       tagged_ans.append(tagged) 
      elif choice == '1': 
       del v1['category'] 
       del value['match'][k1] 

在這種情況下如何保持當前索引和不跳過任何項的迭代。在上面的示例中movie可以跳過

+1

你真正的問題是什麼? – 2014-11-24 07:09:30

+0

@RikVerbeek:對不起,更新了問題 – puncrazy 2014-11-24 07:16:51

+1

不要刪除字典中的鍵,你正在更新字典並同時增加計數器,這就是爲什麼指針在第二次迭代中移動到第三項的原因。 – 2014-11-24 07:38:28

回答

1

您可以簡單地遍歷循環。這樣,您可以根據需要從末尾刪除元素,而不會替換未迭代的元素。

我們可以通過你的枚舉轉換到一個列表,並與reversed包裝這份名單做:

for k1,v1 in reversed(list(enumerate(value['match']))): 
    if k1 != '': 
     print '\n Category: ',k1,' ',v1['category'] 

     print 'Do you want to change the class of entity',k1 ,'? Y/N', 'Or delete', k1, '1/0' 
     choice = raw_input() 
     if choice == 'N' or choice == 'n': 
      pass 
     elif choice == 'Y' or choice == 'y' : 
      print '\tEnter class : \t' 
      v1['category'] = raw_input() 
      tagged = string.replace(sentence, key, v1['category']) 
      tagged_ans.append(tagged) 
     elif choice == '1': 
      del v1['category'] 
      del value['match'][k1] 

因爲我們是鑄造到一個列表,要小心使用這個上非常大的序列。如有必要,有更高效的方法可以在不創建列表的情況下執行此操作(例如itertools)。

+0

謝謝,但得到這個錯誤:TypeError:參數顛倒()必須是一個序列 – puncrazy 2014-11-24 07:31:04

+0

@puncrazy:請參閱我的編輯。 – grovesNL 2014-11-24 14:56:07